【问题标题】:How do i convert 2014-12-19T05:00:00 to proper datatime, 2014-12 in Python如何在 Python 中将 2014-12-19T05:00:00 转换为正确的数据时间,2014-12
【发布时间】:2020-03-24 02:58:39
【问题描述】:

我在数据中得到一个日期,类似于“2014-12-19T05:00:00”。我想对其进行转换以获得日期或字符串对象,并在数据框中获得类似于“01-04-2018”的“dd-MM-YYYY”。我该怎么做? 结果将用于时间序列。到目前为止,我的时间序列结果是这样的,可能是因为它没有检测到日期格式(x轴不在日期时间)。

日期栏:

【问题讨论】:

    标签: python dataframe datetime


    【解决方案1】:

    对于 pandas 数据框列/系列:

    使用to_datetime 将字符串列(object 的数据类型)转换为日期时间列(datetime64[ns] 的数据类型)。然后,如果您想要另一列以您选择的字符串格式返回日期时间,请使用dt.strftime

    一个例子:

    df = pd.DataFrame({
      "Date": ["2014-12-19T05:00:00", "2014-12-20T05:00:00", "2014-12-21T05:00:00"],
      "Value": [0, 2, 4]})
    df['DateTime'] = pd.to_datetime(df['Date'])
    df['MyDateTimeString'] = df['DateTime'].dt.strftime('%Y-%m-%d')
    
    print(df)
    #                   Date  Value            DateTime MyDateTimeString
    # 0  2014-12-19T05:00:00      0 2014-12-19 05:00:00       2014-12-19
    # 1  2014-12-20T05:00:00      2 2014-12-20 05:00:00       2014-12-20
    # 2  2014-12-21T05:00:00      4 2014-12-21 05:00:00       2014-12-21
    

    一般:

    要将您的字符串读入日期时间对象,请使用strptime

    import datetime
    
    d = datetime.datetime.strptime("2014-12-19T05:00:00", "%Y-%m-%dT%H:%M:%S")
    

    然后要获取这些日期时间对象的字符串表示,请使用strftime

    d.strftime("%d-%m-%Y")
    

    对于更一般的字符串到日期时间解析,dateparser 库很方便:

    import dateparser
    
    dateparser.parse("2014-12-19T05:00:00").strftime("%d-%m-%Y")
    # '19-12-2014'
    dateparser.parse("December 19, 2014 at 5am").strftime("%d-%m-%Y")
    # '19-12-2014'
    

    【讨论】:

    • 您知道如何更改数据框中的列,而不是字符串吗?已编辑问题中的列
    • @swm 编辑了我的回复以添加熊猫系列的答案。
    【解决方案2】:

    我推荐使用https://pypi.org/project/python-dateutil/ (使用pip install python-dateutil 安装。)

    >>> import dateutil.parser
    >>> d = dateutil.parser.isoparse('2014-12-19T05:00:00')
    >>> print(d.strftime('%m-%d-%Y'))
    12-19-2014
    

    【讨论】:

    • 你可能会提到,dateutil 不是标准模块,但它必须与pip install python-dateutil一起安装
    猜你喜欢
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    相关资源
    最近更新 更多