【问题标题】:How to get the UNIX time from datetime string with timezone in Python 2.7如何在 Python 2.7 中从带有时区的日期时间字符串中获取 UNIX 时间
【发布时间】:2022-01-01 16:25:54
【问题描述】:

我想从日期时间字符串中获取 UNIX 时间戳,例如“2021-11-20T12:42:00-08:00”。 我搜索了这个解决方案,但没有找到答案。

【问题讨论】:

    标签: python python-2.7 datetime timestamp


    【解决方案1】:

    使用 python-dateutil 这很简单

    from dateutil.parser import parse
    dt = parse('2021-11-20T12:42:00-08:00')
    timestamp = dt.timestamp()
    
    # in py2.7 you cannot use .timestamp so the following should work
    import pytz
    timestamp = time.mktime(dt.astimezone(pytz.utc).timetuple()) 
    

    【讨论】:

    • 在 python 2.7 中可以吗?我收到一个错误“datetime.datetime”对象没有属性“timestamp”
    • nope timestamp 出现在 3+... 用 py2.7 版本编辑错误
    • 我在运行上述代码后得到了数字 1637412120,但是当我在 MySql 中运行 sql 'select FROM_UNIXTIME(1637412120)' 时,日期时间是 2021-11-20 12:42:08。不确定它是否正确。
    • 你应该得到 1637469720.0
    • 令人惊讶的是,Python 2 甚至无法使用 strptime 解析 UTC 偏移量……这是该死的 ISO 格式! ^^ 此外,如果你使用 dateutil,它也是一个 UTC 时区。你不需要 dateutil pytz。
    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    相关资源
    最近更新 更多