JNevens
JNevens

Reputation: 12012

Python: datetime format

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?

Upvotes: 2

Views: 1696

Answers (4)

itchee
itchee

Reputation: 820

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.

Upvotes: 2

jfs
jfs

Reputation: 414795

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)

Upvotes: 1

logic
logic

Reputation: 1727

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

Upvotes: 0

Vor
Vor

Reputation: 35149

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())

Upvotes: 4

Related Questions