Parse a date in a specific timezone with Python
如何获取此日期字符串:
"2015年1月1日"
并且,假设它位于特定时区(例如"US-Mountain"),将其转换为POSIX时间戳?
像这样:
1 | magic_parse_function("2015-01-01", pytz.timezone("US-Mountain")) -> 1420095600 |
我花了很多时间搜索文档和这个网站,玩意识/不知道日期时间对象,并希望有一个不太疯狂的解决方案。 以下不起作用,最后两行输出相同,它们应相隔3600秒:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import datetime import time import pytz timestring ="2015-01-01" pacific = pytz.timezone("US/Pacific") mountain = pytz.timezone("US/Mountain") (year, month, day) = timestring.split('-') year = int(year) month = int(month) day = int(day) unaware = datetime.datetime(year, month, day, 0, 0, 0, 0) # aware_pacific = pacific.localize(unaware) # aware_mountain = mountain.localize(unaware) aware_mountain = unaware.replace(tzinfo=mountain) aware_pacific = unaware.replace(tzinfo=pacific) print time.mktime(aware_pacific.timetuple()) print time.mktime(aware_mountain.timetuple()) |
有三个步骤:
将日期字符串转换为天真的
1 2 3 | from datetime import datetime dt = datetime(*map(int ,'2015-01-01'.split('-'))) |
获取时区感知日期时间对象:
1 2 3 | import pytz # $ pip install pytz aware = pytz.timezone("US/Mountain").localize(dt, is_dst=None) |
获取POSIX时间戳:
1 | timestamp = aware.timestamp() |
从Python 3.3+开始,