I would like to get the timestamp from dates in the following formats:
Mon, 23 Nov 2020 19:00:00 GMT
Mon, 23 Nov 2020 20:00:00 +0100
I am using the the following statements to convert dates to datetime objects:
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
But using .timestamp() method, different seconds from epoch are printed. Why doesn't the %Z directive add timezone information to the datetime object? How could I get the timezone into account, so the timestamp is equal?
Please note Inconsistent datetime parse timezone in Python. Your problem is %Z, it makes strptime accept certain strings (GMT, UTC and any value in time.tzname - docs), but doesn't actually make anything out of it. The returned datetime object is naive - which is why Python will assume it's local time if you call the timestamp() method of it.
You can use dateutil's parser instead:
from dateutil.parser import parse
for s in ("Mon, 23 Nov 2020 19:00:00 GMT", "Mon, 23 Nov 2020 20:00:00 +0100"):
dt = parse(s)
print(repr(dt), dt.timestamp())
# datetime.datetime(2020, 11, 23, 19, 0, tzinfo=tzutc()) 1606158000.0
# datetime.datetime(2020, 11, 23, 20, 0, tzinfo=tzoffset(None, 3600)) 1606158000.0
Related
Trying to parse a date like, "Thu, 22 Oct 2020 17:33:00 UT" with datetime.strptime(). I've tried:
datetime.strptime('Thu, 22 Oct 2020 17:33:00 UT', '%a, %d %b %Y %H:%M:%S %Z')
However, it appears 'UT' is not a recognized timezone. Is this possible without any string manipulation? Any help is much appreciated.
you could use dateutil's parser and supply a tzinfos mapping dict:
import dateutil
timezone_infos = {"UT": dateutil.tz.UTC}
dt = dateutil.parser.parse('Thu, 22 Oct 2020 17:33:00 UT', tzinfos=timezone_infos)
print(dt)
>>> 2020-10-22 17:33:00+00:00
I have a function in my backend and I receive the date from the front end in the formart Wed Dec 14 2016 14:39:16 GMT+0300 (AST)
date = request.body['date']
d = datetime.strptime(date, '%a %b %d %Y %X %Z%z')
I know strptime converts to the datetime object but I keep getting the following
'z' is a bad directive in format '%a %b %d %Y %X %Z%z'
What should my string format be?
You can do like this:
from dateutil import parser
parser.parse("Wed Dec 14 2016 14:39:16 GMT+0300 (AST)")
I have date in string:
Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)
and I use (according to https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior):
datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z')
but I get error:
ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%S %z %Z'
How to do it correctly?
%z is the +0200, %Z is CEST. Therefore:
>>> s = "Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)"
>>> datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=datetime.timezone(datetime.timedelta(0, 7200), 'CEST'))
I also replaced your %m with %d; %m is the month, numerically, so in your case 04 would be parsed as April.
python datetime can't parse the GMT part (You might want to specify it manually in your format). You can use dateutil instead:
In [16]: s = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'
In [17]: from dateutil import parser
In [18]: parser.parse(s)
Out[18]: d = datetime.datetime(2016, 10, 4, 12, 13, tzinfo=tzoffset(u'CEST', -7200))
In [30]: d.utcoffset()
Out[30]: datetime.timedelta(-1, 79200)
In [31]: d.tzname()
Out[31]: 'CEST'
Simpler way to achieve this without taking care of datetime formatting identifiers will be the usage of dateutil.parser(). For example:
>>> import dateutil.parser
>>> date_string = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'
>>> dateutil.parser.parse(date_string)
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=tzoffset(u'CEST', -7200))
If you want to parse all you datetime data in a column in pandas DataFrame, you can use apply method to apply together with dateutil.parser.parse to parse whole column:
from dateutil.parser import parse
df['col_name'] = df['col_name'].apply(parse)
def deadlines(t):
'''shows pretty time to deadlines'''
fmt = '%a %d %m %Y %I:%M %p %Z'
dt = datetime.strptime( t , fmt )
print 'dt ', repr(dt)
first = 'Sun 11 May 2014 05:00 PM PDT'
deadlines(first)
ValueError: time data 'Sun 11 May 2014 02:00 PM PDT' does not match format ' %a %d %m %Y %I:%M %p %Z '
Whats wrong with this?
%m matches months represent as a two-digit decimal (in [01, 12]). Use %b for abbreviated month names, or %B for full month names instead:
fmt = '%a %d %b %Y %I:%M %p %Z'
A table showing the date format directives and their meanings can be found here.
If you're having trouble parsing PDT using %Z:
Per the time.strptime docs:
Support for the %Z directive is based on the values contained in
tzname and whether daylight is true. Because of this, it is
platform-specific except for recognizing UTC and GMT which are always
known (and are considered to be non-daylight savings timezones).
So, if parsing the date string without PDT works:
In [73]: datetime.strptime('Sun 11 May 2014 05:00 PM', '%a %d %b %Y %I:%M %p')
Out[73]: datetime.datetime(2014, 5, 11, 17, 0)
but
datetime.strptime('Sun 11 May 2014 05:00 PM PDT', '%a %d %b %Y %I:%M %p %Z')
raises a ValueError, then you may need strip off the timezone name (they are, in general, ambiguous anyway):
In [10]: datestring = 'Sun 11 May 2014 05:00 PM PDT'
In [11]: datestring, _ = datestring.rsplit(' ', 1)
In [12]: datestring
Out[12]: 'Sun 11 May 2014 05:00 PM'
In [13]: datetime.strptime(datestring, '%a %d %b %Y %I:%M %p')
Out[13]: datetime.datetime(2014, 5, 11, 17, 0)
or use dateutil:
In [1]: import dateutil.parser as parser
In [2]: parser.parse('Sun 11 May 2014 05:00 PM PDT')
Out[2]: datetime.datetime(2014, 5, 11, 17, 0)
I have some doubts in the dateformat Tue Feb 25 2014 00:00:00 GMT+0530 (IST).
does Tue Feb 25 2014 00:00:00 means GMT or IST
Is it possible to convert this into python datetime.
and also is it possible convert it into format DD-MM-YY,HH:MM:SS in GMT.
Here is what i tried to convert into python datetime::
but i got error,when i tried with %z:
>>> time_format="%a %b %d %Y %H:%M:%S GMT%z (%Z)"
>>> v="Tue Feb 25 2014 00:00:00 GMT+0530 (IST)"
>>> mydate=datetime.strptime(v,time_format)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
But this works:
>>> time_format="%a %b %d %Y %H:%M:%S GMT (%Z)"
>>> v="Tue Feb 25 2014 00:00:00 GMT (IST)"
>>> datetime.strptime(v,time_format)
datetime.datetime(2014, 2, 25, 0, 0)
but still didn't understand anything about TIMEZONE.
In the system terminal
easy_install python-dateutil
In the python shell
from dateutil import parser as date_parser
print date_parser.parse("Tue Feb 25 2014 00:00:00 GMT+0530 (IST)")
Dateutil's parse can typically just parse anything you throw at it into a Python datetime.
I think the best way would be to try something like this, especially if you want to avoid using external libraries for example in Python 3.6.9 :
datetime.strptime(v,"%a %b %d %Y %H:%M:%S %Z%z (IST)")