【问题标题】:Python datetime and pandas give different timestamps for the same datePython datetime 和 pandas 为同一日期提供不同的时间戳
【发布时间】:2020-10-20 00:52:07
【问题描述】:
from datetime import datetime
import pandas as pd

date="2020-02-07T16:05:16.000000000"

#Convert using datetime
t1=datetime.strptime(date[:-3],'%Y-%m-%dT%H:%M:%S.%f')

#Convert using Pandas
t2=pd.to_datetime(date)

#Subtract the dates
print(t1-t2)

#subtract the date timestamps
print(t1.timestamp()-t2.timestamp())

在这个例子中,我的理解是 datetime 和 pandas 都应该使用 timezone naive 日期。谁能解释为什么日期之间的差异为零,但时间戳之间的差异不为零?对我来说,时间差了 5 小时,这是我与 GMT 的时区偏移量。

【问题讨论】:

  • "警告由于许多 datetime 方法将幼稚的 datetime 对象视为本地时间,因此最好使用可感知的 datetimes 来表示 UTC 时间。因此,推荐的方法来创建表示特定对象的对象UTC 中的时间戳是通过调用 datetime.fromtimestamp(timestamp, tz=timezone.utc)。"来自 Python 日期时间
  • 本地日期时间返回一个了解您当地时区的时间。

标签: python pandas datetime


【解决方案1】:

Python 的 datetime.datetime 类的朴素日期时间对象表示本地时间。这一点在the docs 中很明显,但仍然可以作为一个脑筋急转弯。如果您在其上调用 timestamp 方法,则返回的 POSIX 时间戳应该是指 UTC(自纪元以来的秒数)。

来自 Python 日期时间对象,天真的 pandas.Timestamp 的行为可能是违反直觉的(我认为这不是那么明显)。从 tz-naive 字符串以相同的方式派生,它不代表当地时间,而是代表 UTC。您可以通过将 datetime 对象本地化为 UTC 来验证这一点:

from datetime import datetime, timezone
import pandas as pd

date = "2020-02-07T16:05:16.000000000"

t1 = datetime.strptime(date[:-3], '%Y-%m-%dT%H:%M:%S.%f')
t2 = pd.to_datetime(date)

print(t1.replace(tzinfo=timezone.utc).timestamp() - t2.timestamp())
# 0.0

反过来,你可以让pandas.Timestamp 感知时区,例如

t3 = pd.to_datetime(t1.astimezone())
# e.g. Timestamp('2020-02-07 16:05:16+0100', tz='Mitteleuropäische Zeit')

# now both t1 and t3 represent my local time:
print(t1.timestamp() - t3.timestamp())
# 0.0

我的底线是,如果您知道您拥有的时间戳代表某个时区,请使用时区感知日期时间,例如对于UTC

import pytz # need to use pytz here since pandas uses that internally

t1 = datetime.strptime(date[:-3], '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=pytz.UTC)
t2 = pd.to_datetime(date, utc=True)

print(t1 == t2)
# True
print(t1-t2)
# 0 days 00:00:00
print(t1.timestamp()-t2.timestamp())
# 0.0

【讨论】:

  • 感谢您的有用解释,现在说得通了。我没有意识到带有 tz=None 的日期时间对象会知道您的本地时区。
  • @Dan:好吧,天真的日期时间对象 表示 当地时间,但有点不知道 - 无论如何,很高兴我能提供帮助;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2020-06-27
  • 2020-08-10
  • 2020-03-29
  • 1970-01-01
  • 2013-02-12
  • 2016-03-21
相关资源
最近更新 更多