【问题标题】:Difference between pandas datetime and datetime datetime熊猫日期时间和日期时间日期时间之间的区别
【发布时间】:2020-10-19 14:43:05
【问题描述】:

您好有一些 datetime.datetime 格式的日期,我用它们来过滤带有熊猫时间戳的熊猫数据框。我刚刚尝试了以下方法并获得了 2 小时的偏移量:

from datetime import datetime
import pandas as pd
pd.to_datetime(datetime(2020, 5, 11, 0, 0, 0).timestamp()*1e9)

输出是:

->Timestamp('2020-05-10 22:00:00')

谁能解释为什么这给出了 2 小时的偏移量?我在丹麦,所以它对应于 GMT 的偏移量。是不是这个原因。我当然可以只增加 2 个小时,但我想了解为什么要让脚本在未来变得健壮。

感谢您的帮助杰斯帕

【问题讨论】:

    标签: python pandas datetime gmt


    【解决方案1】:

    pd.to_datetime 接受 datetime 对象,所以你可以这样做(熊猫假设 UTC):

    pd.to_datetime(datetime(2020, 5, 11))
    

    在转换为时间戳时,您将获得 2 小时的偏移量,因为默认情况下 python 的 datetime 不知道时区,并且会给您一个“天真的”datetime 对象(文档在这里:https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)。生成的时间戳将在本地时区,因此有 2 小时的偏移量。

    您可以将tzinfo 参数传递给datetime 对象,指定应将时间视为UTC:

    from datetime import datetime
    import pandas as pd
    import pytz
    
    pd.to_datetime(datetime(2020, 5, 11, 0, 0, 0, tzinfo=pytz.UTC).timestamp()*1e9)
    

    或者,您可以使用 calendar 模块生成 UTC 时间戳:

    from datetime import datetime
    import pandas as pd
    import calendar
    
    timestamp = calendar.timegm(datetime(2020, 5, 11, 0, 0, 0).utctimetuple())
    pd.to_datetime(timestamp*1e9)
    

    【讨论】:

      【解决方案2】:

      如果您的日期时间对象实际上代表 本地时间(即您的操作系统设置),您可以简单地使用

      from datetime import datetime
      import pandas as pd
      
      t = pd.to_datetime(datetime(2020, 5, 11).astimezone())
      # e.g. I'm on CEST, so t is
      # Timestamp('2020-05-11 00:00:00+0200', tz='Mitteleuropäische Sommerzeit')
      

      见:How do I get a value of datetime.today() in Python that is “timezone aware”?


      请记住,pandas 会将原始 Python 日期时间对象视为 UTC:

      from datetime import timezone
      
      t1 = pd.to_datetime(datetime(2020, 5, 11, tzinfo=timezone.utc))
      t2 = pd.to_datetime(datetime(2020, 5, 11))
      
      t1.timestamp() == t2.timestamp()
      # True
      

      另见:Python datetime and pandas give different timestamps for the same date

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 2016-07-05
        • 1970-01-01
        • 2017-02-23
        • 1970-01-01
        • 1970-01-01
        • 2019-07-19
        • 2022-10-12
        相关资源
        最近更新 更多