简体   繁体   中英

How do I convert a string with a different time zone to a datetime object?

I understand how to convert a string to a datetime object, but what about a string that has a different time zone? for example "10/07/2011 04:22 CEST"

EST can mean two different timezones: European Summer Time, or Eastern Standard Time. So datetime strings such as 08/07/2011 04:22 EST are ambiguous -- there's no sure-fire way to correctly convert such strings to a timezone-aware datetime.

If you are willing to just make a stab at a possibly correct answer, then you can generate a mapping between abbreviations like EST and timezone names, make a random choice among the valid timezones, and then use that timezone to build a timezone-aware datetime:

import dateutil.tz as dtz
import pytz
import datetime as dt
import collections
import random

timezones = collections.defaultdict(list)
for name in pytz.common_timezones:
    timezone = dtz.gettz(name)
    try:
        now = dt.datetime.now(timezone)
    except ValueError:
        # dt.datetime.now(dtz.gettz('Pacific/Apia')) raises ValueError
        continue
    abbrev = now.strftime('%Z')
    timezones[abbrev].append(name) 

date_string, tz_string = '10/07/2011 04:22 CEST'.rsplit(' ', 1)
date = dt.datetime.strptime(date_string, '%m/%d/%Y %H:%M')
print(date)
# 2011-10-07 04:22:00

tz = pytz.timezone(random.choice(timezones[tz_string]))
print(tz)
# Europe/Oslo

date = tz.localize(date)
print(date)
# 2011-10-07 04:22:00+02:00

You should be able to use strptime with a %Z in your format string, but be aware of this note from the Python documentation (http://docs.python.org/library/datetime.html#strftime-strptime-behavior):

"%Z -- If tzname() returns None, %Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string. The full set of format codes supported varies across platforms, because Python calls the platform C library's strftime() function, and platform variations are common."

Can you put the timezone into offset form and use %z instead?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM