gpt4 book ai didi

python - 在python2.7中将时间戳字符串转换为带或不带时区的Unix时间

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:07 26 4
gpt4 key购买 nike

我正在尝试将给定字符串转换为 Unix 时间。该字符串中始终包含时间,并且还可以选择包含日期。例如,12/31/15 11:59PM12/31/15 11:5911:59 是我可以期待得到。

使用以下内容,任何这些字符串都可以正确转换:

from dateutil import parser 
import time

timezone = "12/31/15 11:59"
target = time.mktime(parser.parse(timestamp).timetuple())

但是,如果也给出时区,例如12/31/15 11:59PM PST,时区被 timetuple() 删除,虽然转换有效,但它仍然会给出与时区没有相同的结果't 在字符串中(因此仅对于系统的本地时间是正确的)。

我还没有找到一种优雅的方法来 1) 在给定时区时正确地将字符串转换为适当的时区,同时 2) 允许存在时区字符串,或者如果缺少,则假设本地时区.

最佳答案

输入的时间字符串可能不明确:

  • 11:59:UTC 偏移量可能取决于日期,例如,夏季时间可能会有所不同。要消除日期歧义,您可以将 default 参数传递给 .parse() 方法
  • PST may correspond to different timezones 。要消除 utc 偏移量的歧义,您可以传递 tzinfos 参数

mktime() 在某些系统上或 DST 转换期间可能会失败。 tzlocal 实现可移植解决方案:

#!/usr/bin/env python
from datetime import datetime
from dateutil.parser import parse # $ pip install python-dateutil
from pytz import utc # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal

epoch = datetime(1970, 1, 1, tzinfo=utc) # POSIX Epoch
default = datetime(2016, 1, 1)
tzinfos = dict(PST=-8 * 3600)
tz = get_localzone() # local timezone
for time_string in ["12/31/15 11:59PM", "12/31/15 11:59PM PST", "12/31/15 11:59",
"11:59"]:
dt = parse(time_string, default=default, tzinfos=tzinfos)
if dt.tzinfo is None or dt.utcoffset() is None: # naive
dt = tz.normalize(tz.localize(dt)) # assume local timezone
posix_timestamp = (dt - epoch).total_seconds()
dt = datetime.fromtimestamp(posix_timestamp, dt.tzinfo)
print("{dt} <- {posix_timestamp:.0f} <- {time_string}".format(**vars()))

输出

2015-12-31 23:59:00+01:00 <- 1451602740 <- 12/31/15 11:59PM
2015-12-31 23:59:00-08:00 <- 1451635140 <- 12/31/15 11:59PM PST
2015-12-31 11:59:00+01:00 <- 1451559540 <- 12/31/15 11:59
2016-01-01 11:59:00+01:00 <- 1451645940 <- 11:59

tz.localize() 使用 is_dst=False 来消除 DST 转换期间的时间歧义或对于不存在的本地时间,请参阅 "Can I just always set is_dst=True?" section .

关于python - 在python2.7中将时间戳字符串转换为带或不带时区的Unix时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com