python - python 中的 Dateutil 解析错误返回错误的值

标签 python python-2.7 parsing python-dateutil

我已经研究了许多解析 python 时间的可能方法。 Using parse seems link the only method that should workWhile trying to use datetime.strptime causes an error because %z does not work with python 2.7 。但使用 parse.parse 会错误地识别时区。

我解析了 Fri Nov 9 09:04:02 2012 -0500Fri Nov 9 09:04:02 2012 -0800 并获得了完全相同的时间戳Unix 时间。 1352480642

  • 我的 python 版本 2.7.10
  • 我的 dateutil 1.5 版本

这是我运行测试的代码。

#!/usr/bin/python
import time
from dateutil import parser

def get_timestamp(time_string):
    timing = parser.parse(time_string)
    return time.mktime(timing.timetuple())

test_time1 = "Fri Nov 9 09:04:02 2012 -0500"
test_time2 = "Fri Nov 9 09:04:02 2012 -0800"
print get_timestamp(test_time1)
print get_timestamp(test_time2)

输出

1352480642.0
1352480642.0

预期输出

1352469842.0
1352480642.0

最佳答案

这与解析器无关,您将仅从 mktime() 看到相同的行为,因为 datetime.timetuple() 没有任何时区偏移信息,并且 mktime()localtime 的倒数。您可以通过在调用 timetuple() 之前将其转换为 localtime 来纠正此问题:

from time import mktime
from datetime import datetime
from dateutil import tz

dt_base = datetime(2012, 11, 9, 9, 4, 2)

dt_est = dt_base.replace(tzinfo=tz.tzoffset('EST', -5 * 3600))
dt_pst = dt_base.replace(tzinfo=tz.tzoffset('PST', -8 * 3600))

def print_mktime(dt):
    print(mktime(dt.timetuple()))

# Run in UTC
print_mktime(dt_est)   # 1352469842.0
print_mktime(dt_pst)   # 1352469842.0

# Convert to local time zone first first
print_mktime(dt_est.astimezone(tz.tzlocal())) # 1352469842.0
print_mktime(dt_pst.astimezone(tz.tzlocal())) # 1352480642.0

请注意,documentation for time() 上有一个图表。 ( python 2.x docs ) 告诉您如何在这些表示形式之间进行转换:

From                        To                           Use
---------------------------------------------------------------------------
seconds since the epoch   | struct_time in UTC        |  gmtime()
seconds since the epoch   | struct_time in local time |  localtime()
struct_time in UTC        | seconds since the epoch   |  calendar.timegm()
struct_time in local time | seconds since the epoch   |  mktime()

我个人的偏好是将解析的日期转换为 UTC,在这种情况下 calendar.timegm() 将是合适的函数:

from calendar import timegm
def print_timegm(dt):
    print(timegm(dt.timetuple()))

print_timegm(dt_est.astimezone(tz.tzutc())) # 1352469842.0
print_timegm(dt_pst.astimezone(tz.tzutc())) # 1352480642.0

关于python - python 中的 Dateutil 解析错误返回错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38963653/

相关文章:

python - python中的稀疏表示数据文件

c++ - token 的类层次结构并在解析器中检查它们的类型

arrays - 解码 map 和 array json

python - 有没有办法在 Python 中获取目录中的所有目录而不是文件?

PHP 非持久进程设计 vs Python/Java

python - 在没有 aux.xml 文件的情况下使用更新的元数据标记创建 geotiff 文件

python - 基于 pyparsing 的分割

python - 使用 matplotlib 填充平均值和曲线波动?

python - 如何在 python 中使用 lzop 压缩和解压缩文件?

python - 线程停止得太早