Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python converting date/time string with a timezone offset

Tags:

python

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?

like image 415
Patrick Weiß Avatar asked Feb 07 '23 15:02

Patrick Weiß


1 Answers

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

like image 53
bakkal Avatar answered Feb 16 '23 03:02

bakkal