Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python time to age, part 2: timezones [duplicate]

Tags:

Following on from my previous question, Python time to age, I have now come across a problem regarding the timezone, and it turns out that it's not always going to be "+0200". So when strptime tries to parse it as such, it throws up an exception.

I thought about just chopping off the +0200 with [:-6] or whatever, but is there a real way to do this with strptime?

I am using Python 2.5.2 if it matters.

>>> from datetime import datetime >>> fmt = "%a, %d %b %Y %H:%M:%S +0200" >>> datetime.strptime("Tue, 22 Jul 2008 08:17:41 +0200", fmt) datetime.datetime(2008, 7, 22, 8, 17, 41) >>> datetime.strptime("Tue, 22 Jul 2008 08:17:41 +0300", fmt) Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib/python2.5/_strptime.py", line 330, in strptime     (data_string, format)) ValueError: time data did not match format:  data=Tue, 22 Jul 2008 08:17:41 +0300  fmt=%a, %d %b %Y %H:%M:%S +0200 
like image 229
Ashy Avatar asked Feb 08 '09 21:02

Ashy


People also ask

Is Strptime aware a timezone?

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

How do you get different time zones in Python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.

What is Tzinfo Python?

tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.


1 Answers

is there a real way to do this with strptime?

No, but since your format appears to be an RFC822-family date, you can read it much more easily using the email library instead:

>>> import email.utils >>> email.utils.parsedate_tz('Tue, 22 Jul 2008 08:17:41 +0200') (2008, 7, 22, 8, 17, 41, 0, 1, 0, 7200) 

(7200 = timezone offset from UTC in seconds)

like image 190
bobince Avatar answered Nov 10 '22 01:11

bobince