【问题标题】:Trying to convert a column in a CSV file from UTC time to US/Pacific time尝试将 CSV 文件中的列从 UTC 时间转换为美国/太平洋时间
【发布时间】:2021-09-05 06:53:40
【问题描述】:

所以我的任务是读取 CSV 文件并将发送电子邮件的时间列转换为新时区(从 UTC 到太平洋) df_emails = df_emails.EmailSentDateTimeUtc.dt.tz_localize('US/Eastern', ambiguous='infer') 我尝试将模糊设置为 true 以及 raise,“EmailSentDateTimeUtc”列已转换为 datetime64[ns] 我正在尝试本地化到东部,然后转换为太平洋。

该代码引发的错误是 AmbiguousTimeError: 2018-11-04 01:58:16.743000

在这里慢慢失去理智,非常感谢任何帮助!

【问题讨论】:

    标签: python pandas time timezone


    【解决方案1】:

    如果您读取 UTC 格式的日期/时间数据,您应该在导入 / 从字符串转换为日期时间数据类型时指定。那么转换到另一个时区不会导致任何错误。

    前:

    import pandas as pd
    
    df_emails = pd.DataFrame({"EmailSentDateTimeUtc": ["2018-11-04 01:58:16.743000"]})
    
    # to datetime, and specifiy that input is UTC
    df_emails.EmailSentDateTimeUtc = pd.to_datetime(df_emails.EmailSentDateTimeUtc, utc=True)
    
    # now you can convert easily like
    df_emails.EmailSentDateTimeUtc = df_emails.EmailSentDateTimeUtc.dt.tz_convert('US/Eastern')
    
    # df_emails
    #               EmailSentDateTimeUtc
    # 0 2018-11-03 21:58:16.743000-04:00
    

    【讨论】:

    • 非常感谢!现在运行完美,非常感谢您的回复!
    猜你喜欢
    • 2011-03-13
    • 2021-03-02
    • 2018-09-15
    • 2014-11-25
    • 2012-12-08
    • 2015-12-31
    • 2018-10-04
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多