2

How can I parse a time string, such as Sun May 27 13:02:04 +0200 2012, to a tuple in UTC, using python3? The closest I can get is time.strptime(str, '%a %b %d %H:%M:%S %z %Y'), but it seems the offset is parsed but ignored. The above example is parsed to:

time.struct_time(tm_year=2012, tm_mon=5, tm_mday=27, tm_hour=13, tm_min=1, tm_sec=35, tm_wday=6, tm_yday=148, tm_isdst=-1)

but I expected tm_hour=11.

Related: Convert string timestamp (with timezone offset) to local time. . ? python, Parsing time string in Python. Answers to both suggests the use of dateutil, but I'd prefer using the standard library, if possible.

Community
  • 1
  • 1
moatPylon
  • 2,103
  • 1
  • 15
  • 22

1 Answers1

2

tm_hour=11 would be incorrect. The time in the timestamp is 13:02:04, no matter what the offset is.

What you want to do is to convert that timestamp into a time in GMT, which the standard library won't do for you. So you will just have to extract the offset yourself (which is trivial) and then subtract it from the time.

I'd also recommend you to use the datetime library for this, date/time manipulation is much easier there, you can easily create a timedelta object from the offset and subtract that from the datetime object.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251