Patrick Weiß
Patrick Weiß

Reputation: 456

Python converting date/time string with a timezone offset

I have something like Fri Aug 03 15:16:37 +0000 2012 and I want to convert it to 03-08-2012.

I also have some dates as Unix timestamp like 1344006622, and here I am simply do:

datetime.datetime.fromtimestamp(1344006622).strftime('%d-%m-%Y')

But this works only for the Unix timestamp. How can I convert the first one?

Upvotes: 4

Views: 2786

Answers (1)

bakkal
bakkal

Reputation: 55448

Python 2 with dateutil

As far as I know, Python 2 only provides a %Z (capital Z) for timezone names, but you have an offset (+0000), but there is a library called dateutil that can help you:

>>> import dateutil
>>> import dateutil.parser
>>> dateutil.parser.parse('Fri Aug 03 15:16:37 +0000 2012')
datetime.datetime(2012, 8, 3, 15, 16, 37, tzinfo=tzutc())

In the above example I used Python 2.7.9 with dateutil 2.4.2 You can check your version with

>>> dateutil.__version__
'2.4.2'

You can install it with pip install python-dateutil or if you want to specify a version pip install python-dateutil==2.4.2

Python 3

Since Python 3.2 there is a %z that parses the +0000 timezone info:

>>> from datetime import datetime
>>> datetime.strptime('Fri Aug 03 15:16:37 +0000 2012', '%a %b %d %H:%M:%S %z %Y')
datetime.datetime(2012, 8, 3, 15, 16, 37, tzinfo=datetime.timezone.utc)

For an explanation of the parameters used please refer to this table

Upvotes: 8

Related Questions