使用Python解析特定时区的日期

时间:2015-11-21 03:48:16

标签: python datetime time timezone pytz

如何获取此日期字符串:

" 2015年1月1日"

并且,假设它在特定时区(例如" US-Mountain"),将其转换为POSIX时间戳?

像这样:

magic_parse_function("2015-01-01", pytz.timezone("US-Mountain")) -> 1420095600

我花了很长时间搜索文档和这个网站,玩意识/不知道日期时间对象,并且希望获得一个不太疯狂的解决方案。以下不起作用,最后两行输出相同,它们应相隔3600秒:

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 个答案:

答案 0 :(得分:3)

有三个步骤:

  1. 将日期字符串转换为天真的datetime对象:

    from datetime import datetime 
    
    dt = datetime(*map(int ,'2015-01-01'.split('-')))
    
  2. 获取时区感知日期时间对象:

    import pytz # $ pip install pytz
    
    aware = pytz.timezone("US/Mountain").localize(dt, is_dst=None)
    

    is_dst=None针对模糊或不存在的时间引发异常。这里' re more details about what is is_dst flag and why do you need it, see "Can I just always set is_dst=True?" section

  3. 获取POSIX时间戳:

    timestamp = aware.timestamp()
    
    从Python 3.3+开始,

    .timestamp()可用。请参阅multiple solutions for older Python versions