【问题标题】:How to convert a datetime ('2019-06-05T10:37:29.353+0100') to UTC timestamp using Python3?如何使用 Python3 将日期时间 ('2019-06-05T10:37:29.353+0100') 转换为 UTC 时间戳?
【发布时间】:2020-09-15 12:28:42
【问题描述】:

我想将datetime,即2019-06-05T10:37:29.353+0100,转换为Python3中的UTC时间戳。

我了解+0100 代表时区。为什么+0100+0200+0300都转换为相同的时间戳?

如何将包含时区的 datetime 转换为 UTC 时间戳?

>>> d=datetime.datetime.strptime('2019-06-05T10:37:29.353+0100', '%Y-%m-%dT%H:%M:%S.%f%z')
>>> unixtime = time.mktime(d.timetuple())
>>> unixtime
1559723849.0
>>> d=datetime.datetime.strptime('2019-06-05T10:37:29.353+0200', '%Y-%m-%dT%H:%M:%S.%f%z')
>>> unixtime = time.mktime(d.timetuple())
>>> unixtime
1559723849.0
>>> d=datetime.datetime.strptime('2019-06-05T10:37:29.353+0300', '%Y-%m-%dT%H:%M:%S.%f%z')
>>> unixtime = time.mktime(d.timetuple())
>>> unixtime
1559723849.0

【问题讨论】:

  • 你可以直接使用日期时间对象的timestamp()方法
  • 顺便说一句。很遗憾fromisoformat 无法解析这个(尽管 ISO 8601 兼容)

标签: python python-3.x datetime


【解决方案1】:

这里有一些更多的解释(见 cmets)如何在时间戳之间来回转换,作为带有 UTC 偏移量和 POSIX 时间戳的字符串。

from datetime import datetime, timezone

s = '2019-06-05T10:37:29.353+0100'
# to datetime object
dt = datetime.strptime('2019-06-05T10:37:29.353+0100', '%Y-%m-%dT%H:%M:%S.%f%z')
# note that the object has tzinfo set to a specific timedelta:
print(repr(dt))
>>> datetime.datetime(2019, 6, 5, 10, 37, 29, 353000, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))

# you could store this info
dt_UTCoffset = dt.utcoffset() # datetime.timedelta(seconds=3600)

# to get POSIX seconds since the epoch:
ts = dt.timestamp()

# and back to datetime:
dt_from_ts = datetime.fromtimestamp(ts, tz=timezone.utc)
# note that this is a UTC timestamp; the UTC offset is zero:
print(dt_from_ts.isoformat())
>>> 2019-06-05T09:37:29.353000+00:00

# instead of UTC, you could also set a UTC offset:
dt_from_ts = datetime.fromtimestamp(ts, tz=timezone(dt_UTCoffset))
print(dt_from_ts.isoformat())
>>> 2019-06-05T10:37:29.353000+01:00

...关于在 Python 中使用 datetime 时的一个陷阱:如果您将时间戳转换为 datetime 并且不设置 tz 属性,则返回本地时间(同样适用于其他方式'轮!):

print(datetime.fromtimestamp(ts)) # I'm on CEST at the moment, so UTC+2
>>> 2019-06-05 11:37:29.353000

【讨论】:

  • 谢谢。我也在 UTC+2(丹麦)。那么您的示例时间(当地时间)不应该是~9.30吗?此外,给定 UTC 时间(UTC 偏移量为 0),总能推导出该点的本地时间,对吗?我不需要将您的dt_UTCoffset 存储在数据库中吗?
  • @Shuzheng:我的示例中的输入是 ~9:37h UTC,所以 11:37 UTC+2。 Python 可以根据操作系统设置确定本地时间。如果您需要确定特定时区,则需要像tzlocal 这样的第三方库。
猜你喜欢
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 2011-05-02
  • 2021-06-14
  • 1970-01-01
相关资源
最近更新 更多