【问题标题】:How to parse the ISO format datetime string in python?如何在python中解析ISO格式的日期时间字符串?
【发布时间】:2020-05-20 19:18:59
【问题描述】:

在 pandas 中,我们如何从这些数据中创建日期时间列?


df = pd.DataFrame({'date': ['2020-02-04T22:03:44.846000+00:00']})
print(df)
                               date
0  2020-02-04T22:03:44.846000+00:00

我不确定这里的字母“T”是什么。

尝试

pat = '%y-%m-%dT%H:%M%:%SZ'
df['date'] = pd.to_datetime(df['date'],format=pat)

I am not sure what is the correct format here.

【问题讨论】:

  • @Felipe,谢谢我明白了,但现在正在努力正确的日期时间格式。

标签: python pandas datetime


【解决方案1】:

感谢@Felipe,

我得到了答案。


df['date'] = pd.to_datetime(df['date'],infer_datetime_format=True)

df = pd.DataFrame({'date': ['2020-02-04T22:03:44.846000+00:00']})

df['year'] = df['date'].dt.year
print(df)

                              date  year
0 2020-02-04 22:03:44.846000+00:00  2020

【讨论】:

    【解决方案2】:

    您可以使用此参考解析日期时间字符串格式: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

    import numpy as np
    import pandas as pd
    
    pd.options.display.max_columns = 10
    pd.set_option('display.max_colwidth', -1)
    
    df = pd.DataFrame({'date': ['2020-02-04T22:03:44.846000+00:00']})
    
    df['date1'] = pd.to_datetime(df['date'],format='%Y-%m-%dT%H:%M:%S.%f%z')
    df['date2'] = pd.to_datetime(df['date'],infer_datetime_format=True)
    df['hour'] = df['date1'].dt.hour
    
    print(df)
    
    0  2020-02-04T22:03:44.846000+00:00 2020-02-04 22:03:44.846000+00:00   
    
                                 date2  hour  
    0 2020-02-04 22:03:44.846000+00:00  22  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多