I have some strings which come to me in formats like
29-Jul-2014 or 03-Aug-2015
What is the easiest way to convert this to a datetime.date object?
I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...} and then do
dt = datetime.date(year, d[month], day)
Is there any other easier way and avoid the creation of this dictionary?
Thanks
Use datetime.datetime.strptime to convert the string to datetime.datetime object.
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)
Then, use datetime.datetime.date method to convert it to datetime.date object:
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
The easy way is use dateutil.parse module, it lets to parse the common date formats, even if you don't know what it is using currently
Ex:
>>> import dateutil.parser
>>>
>>> utc_time = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)
Once you have a datetime object, you only should invoke the datetime.date() method
Related
I want to filter my list of time string elements with the help of python datetime library.
I have a array like -
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
I want to make it be filtered from the ascending order (0:0:0 - 23:59:59) accordingly.
Also i will have bulk of data (array should be almost containing more than 5k ) so what will be most efficient for this?
How can i achieve this in python?
the resulting array should be something like -
["0:0:16","2:50:32","3:59:9","20:30:12","23:46:52"]
This will convert the strings to datetime, sort them then output a list with your desired format.
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
sorted(time_Arr, key=lambda x: datetime.strptime(x, '%H:%M:%S'))
['0:0:16', '2:50:32', '3:59:9', '20:30:12', '23:46:52']
Use datetime to parse the time then sort:
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
time_Arr = sorted([datetime.strptime(t, "%H:%M:%S") for t in time_Arr])
# [datetime.datetime(1900, 1, 1, 0, 0, 16),
# datetime.datetime(1900, 1, 1, 2, 50, 32),
# datetime.datetime(1900, 1, 1, 3, 59, 9),
# datetime.datetime(1900, 1, 1, 20, 30, 12),
# datetime.datetime(1900, 1, 1, 23, 46, 52)]
from datetime import datetime
sorted([datetime.strptime(time, "%H:%M:%S") for time in time_Arr])
Is there any one liner method to convert datetime to simple tuple
>>> from datetime import datetime, timedelta
>>> new_date = datetime. today() + timedelta(12)
>>> new_date
datetime.datetime(2020, 5, 26, 13, 31, 36, 838650)
How do I convert new_date to tuple type.
This is what I have tried
tuple(new_date)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
tuple(new_date)
TypeError: 'datetime.datetime' object is not iterable
Expected output :
>> (2020, 5, 26, 13, 31, 36, 838650)
If you want to "customize" the output (e.g. including microseconds), you could use attrgetter from the operator module to get the attributes from the datetime object.
from datetime import datetime
from operator import attrgetter
attrs = ('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond')
d = datetime.now()
# datetime.datetime(2020, 5, 14, 12, 49, 35, 33067)
d_tuple = attrgetter(*attrs)(d)
# (2020, 5, 14, 12, 49, 35, 33067)
Otherwise, just use the timetuple() as shown in the other answers (probably more efficient if you can live without microseconds).
There is a timetuple you can use.
>>> new_date.timetuple()
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=26, tm_hour=11, tm_min=15, tm_sec=30, tm_wday=1, tm_yday=147, tm_isdst=-1)
>>> tuple(new_date.timetuple())
(2020, 5, 26, 11, 15, 30, 1, 147, -1)
You do not actually need to convert it to a tuple, the above is just to make a point. You can use it where you use a normal tuple.
Please, use timetuple() or utctimetuple() for the conversion:
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2020, 5, 14, 17, 18, 39, 958430)
>>> dt.timetuple()
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=14, tm_hour=17, tm_min=18, tm_sec=39, tm_wday=3, tm_yday=135, tm_isdst=-1)
>>>
I have an issue that I am encountering with one of the modules. Due to the requirement of data handlers, one of the modules has to use the datetime library and the strptime function. But the code behavior does not seem to be consistent, when the left most zero from a date series in format MMDDYYYY is truncated especially for Jan month. Below are some example,you can see the 2nd and third command are identical but the month is getting corrupted. Anyways around how to handle it?
>>> datetime.strptime('01082018',"%m%d%Y")
datetime.datetime(2018, 1, 8, 0, 0)
>>> datetime.strptime('1082018',"%m%d%Y")
datetime.datetime(2018, 10, 8, 0, 0)
>>> datetime.strptime('8082018',"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)
>>> datetime.strptime('08082018',"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)
You can try to split it in two multiple commands and append a zero (if need be)
>>> date_str = '01082018'
>>> if len(date_str)==7:
>>> date_str = '0'+date_str
>>> datetime.strptime(date_str ,"%m%d%Y")
datetime.datetime(2018, 1, 8, 0, 0)
AND
>>> date_str = '8082018'
>>> if len(date_str)==7:
>>> date_str = '0'+date_str
>>> datetime.strptime(date_str ,"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)
I have a date time format where dates are represented as integers from 1/1/1900 .
For example: 1 is 1/1/1900 and 42998 is 20/9/2017.
How can I convert this format to a human readable format like dd/mm/yyyy ? I checked datetime documentation but I did not find any way to do this. I want to do this either on python 3 or 2.7.
Thanks for any suggestion.
You can define your dates as offsets from your basetime and construct a datetime:
In[22]:
import datetime as dt
dt.datetime(1900,1,1) + dt.timedelta(42998)
Out[22]: datetime.datetime(2017, 9, 22, 0, 0)
Once it's a datetime object you can convert this to a str via strftime using whatever format you desire:
In[24]:
(dt.datetime(1900,1,1) + dt.timedelta(42998-1)).strftime('%d/%m/%Y')
Out[24]: '21/09/2017'
So you can define a user func to do this:
In[27]:
def dtToStr(val):
base = dt.datetime(1900,1,1)
return (base + dt.timedelta(val-1)).strftime('%d/%m/%Y')
dtToStr(42998)
Out[27]: '21/09/2017'
import datetime
base_date = datetime.datetime(1900, 1, 1)
convert = lambda x: base_date + datetime.timedelta(days=x-1)
>>> convert(42998)
datetime.datetime(2017, 9, 21, 0, 0)
You can use a datetime object to do that.
import datetime
d = datetime.datetime(1900, 1, 1, 0, 0)
d + datetime.timedelta(days = 42998)
>> datetime.datetime(2017, 9, 22, 0, 0)
I want to create a parse function with lambda able to recognize two different formats
"2014-01-06 15:23:00"
and
"2014-01-06"
The idea is to use this function to create a pandas dataframe but in some of the values the hour is missing
This is my first idea
parse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') if x is True else pd.datetime.strptime(x, '%Y-%m-%d')
it seems that x is True is not correct
Any idea??
dateutil has a parser that handles multiple formats:
>>> dateutil.parser.parse('2015-07-04')
datetime.datetime(2015, 7, 4, 0, 0)
>>> dateutil.parser.parse('2015-07-04 11:23:00')
datetime.datetime(2015, 7, 4, 11, 23)
>>> dateutil.parser.parse('2015-07-04T11:23:56')
datetime.datetime(2015, 7, 4, 11, 23, 56)
Even non iso formats like this
>>> dateutil.parser.parse('5-6-15')
datetime.datetime(2015, 5, 6, 0, 0)