毫秒去哪儿了?
这是最简单的部分。 .timetuple() 电话会挂断他们。您可以使用 .microsecond 属性将它们添加回来。 datetime.timestamp() method from the standard library 以这种方式适用于天真的日期时间对象:
def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
return _time.mktime((self.year, self.month, self.day,
self.hour, self.minute, self.second,
-1, -1, -1)) + self.microsecond / 1e6
else:
return (self - _EPOCH).total_seconds()
如果可能的话,在您的情况下可以忽略约 1 小时的错误就足够了。我假设您需要微秒,因此您不能默默地忽略约 1 小时的时间错误。
将作为字符串给出的本地时间正确转换为 POSIX 时间戳通常是一项复杂的任务。您可以将本地时间转换为 UTC,然后将 get the timestamp from UTC time.
主要有两个问题:
两者都可以使用 tz 数据库(Python 中的pytz 模块)解决:
from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # get pytz timezone corresponding to the local timezone
naive_d = datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
# a) raise exception for non-existent or ambiguous times
d = tz.localize(naive_d, is_dst=None)
## b) assume standard time, adjust non-existent times
#d = tz.normalize(tz.localize(naive_d, is_dst=False))
## c) assume DST is in effect, adjust non-existent times
#d = tz.normalize(tz.localize(naive_d, is_dst=True))
timestamp = d - datetime(1970, 1, 1, tzinfo=pytz.utc)
结果是timestamp -- 一个timedelta 对象,你可以将其转换为秒、毫秒等。
此外,不同的系统在闰秒前后的行为可能不同。大多数应用程序可以忽略它们的存在。
通常,将 POSIX 时间戳存储到本地时间可能更简单,而不是尝试从本地时间猜测它。