2

I have the following datetime string:

Mon Oct 27 23:00:03 +0000 2014

I would like to convert this string to a form where I could compare the datetimes. So, the first thing I tried is converting this to a datetime in Python.

I am having trouble with the correct formatting. I have followed the documentation, but it does not work.

I have tried the following:

str = 'Mon Oct 27 23:00:03 +0000 2014'
datetime.strptime(str, '%a %b %d %X %Z %Y')

How can I get this to work?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
JNevens
  • 11,202
  • 9
  • 46
  • 72
  • related: [Python: parsing date with timezone from an email](http://stackoverflow.com/q/1790795/4279) – jfs Mar 25 '15 at 19:11
  • unrelated: don't use `str` as a name. It shadows the Python builtin. – jfs Mar 26 '15 at 07:24
  • @J.F.Sebastian Yes, I know, but it was just an example. In my code, I don't use str as a variable name. – JNevens Mar 26 '15 at 08:56

4 Answers4

4

If you want to convert it to the datetime object you can use library python-dateutil.

For example:

In [6]: dateutil.parser.parse('Mon Oct 27 23:00:03 +0000 2014')
Out[6]: datetime.datetime(2014, 10, 27, 23, 0, 3, tzinfo=tzutc())
Vor
  • 33,215
  • 43
  • 135
  • 193
2

In Python 3.2+:

>>> from datetime import datetime
>>> timestr = 'Mon Oct 27 23:00:03 +0000 2014'
>>> datetime.strptime(timestr, '%a %b %d %X %z %Y')
datetime.datetime(2014, 10, 27, 23, 0, 3, tzinfo=datetime.timezone.utc)

Note the lower case %z.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
itchee
  • 820
  • 5
  • 20
1

Here's a stdlib-only version that works on Python 2 and 3:

#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz

timestamp = mktime_tz(parsedate_tz('Mon Oct 27 23:00:03 +0000 2014'))
utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2014, 10, 27, 23, 0, 3)

where utc_dt is a datetime object that represents time in UTC timezone (regardless of the input timezone).

Note: it doesn't support the time that represents a leap second (though datetime object can't represent it anyway):

>>> datetime.utcfromtimestamp(mktime_tz(parsedate_tz('Tue June 30 23:59:60 +0000 2015')))
datetime.datetime(2015, 7, 1, 0, 0)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

Your problem lies with your %z UTC offset value (you should've used a lowercase z). However,

%z is only supported in Python 3.2+

If you are stuck with an older version of Python, you could possibly take out the UTC offset from the string and try converting it after you convert the rest

logic
  • 1,739
  • 3
  • 16
  • 22