【问题标题】:Convert python aware datetime to local timetuple将 python 感知日期时间转换为本地时间元组
【发布时间】:2018-08-30 02:38:42
【问题描述】:

我有一个知道的datetime 对象:

dt = datetime.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))

我正在使用它来将对象转换为时间戳,它目前运行良好:

int(time.mktime(dt.utctimetuple()))

但根据time docstime.mktime 需要本地timetuple,而不是UTC timetuple。如何从有意识的datetime 获得本地timetuple?或者有没有其他方法可以制作timestamp 而不是time.mktime

我已经阅读了这个问题,看来我应该使用calendar.timegm(dt.utctimetuple())Converting datetime to unix timestamp

【问题讨论】:

  • 不清楚您要在这里做什么?你知道datetime,你会得到什么?
  • 我要获取datetime对应的Unix时间戳。
  • 所以time.mktime 是错误的。
  • 顺便说一句,您应该在问题中添加您的评论。

标签: python datetime epoch python-datetime


【解决方案1】:

如果您知道日期时间,则可以通过减去 UTC 纪元的日期时间,将其转换为 unix 纪元时间戳:

代码:

import datetime as dt
import pytz

def aware_to_epoch(aware):
    # get a datetime that is equal to epoch in UTC
    utc_at_epoch = pytz.timezone('UTC').localize(dt.datetime(1970, 1, 1))

    # return the number of seconds since epoch
    return (aware - utc_at_epoch).total_seconds()

aware = dt.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))
print(aware_to_epoch(aware))

结果:

1521612302.341014

【讨论】:

    【解决方案2】:

    您似乎对自己想要什么感到困惑。

    根据您的评论,答案在 python datetime 文档中:

    没有直接从表示 UTC 时间的简单日期时间实例获取 POSIX 时间戳的方法。如果您的应用程序使用此约定并且您的系统时区未设置为 UTC,您可以通过提供 tzinfo=timezone.utc 来获取 POSIX 时间戳:

    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
    

    或者直接计算时间戳:

    时间戳 = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

    【讨论】:

    • dt 是时区感知的,它在 UTC+7 中。 int(time.mktime(dt.timetuple())) 返回错误结果。
    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2021-05-02
    相关资源
    最近更新 更多