Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string with UTC offset to a datetime object [duplicate]

Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object?

After doing some reading I feel like this should work, but it doesn't...

>>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fmt) Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime     (bad_directive, format)) ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z' 

It should be noted that this works without a problem:

>>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50' >>> fmt = '%a, %d %b %Y %H:%M:%S' >>> datetime.strptime(str, fmt) datetime.datetime(2010, 4, 9, 14, 10, 50) 

But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way.

like image 633
Gussi Avatar asked Apr 09 '10 16:04

Gussi


People also ask

How do I convert UTC to datetime in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.

How do you convert datetime to UTC?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

How do you format UTC time in Python?

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime. astimezone() method to convert the datetime to UTC.


1 Answers

It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.

Note: from Python 3.2 onwards it will always work.

like image 98
clahey Avatar answered Oct 18 '22 05:10

clahey