【问题标题】:Changing datetime format which includes weekday?更改包含工作日的日期时间格式?
【发布时间】:2021-03-04 17:10:49
【问题描述】:

目前我有这种格式的日期时间列

        Datime
        Thu Jun 18 23:04:19 +0000 2020
        Thu Jun 18 23:04:18 +0000 2020
        Thu Jun 18 23:04:14 +0000 2020
        Thu Jun 18 23:04:13 +0000 2020

我想改成:

   Datetime
 2020-06-18 23:04:19
 2020-06-18 23:04:18
 2020-06-18 23:04:14
 2020-06-18 23:04:13

【问题讨论】:

    标签: python pandas date datetime timestamp


    【解决方案1】:

    假设您已经加载了 pandas 数据框,您可以使用此函数将 Datetime 列转换为指定格式。您可以重命名此函数。

    import datetime
    
    def modify_datetime(dtime):
        my_time = datetime.datetime.strptime(dtime, '%a %b %d %H:%M:%S %z %Y')
        return my_time.strftime('%Y-%m-%d %H:%M:%S')
    

    strptime 函数的第一个参数是日期字符串,第二个参数是格式。

    Directive, Description
    
    %a         Weekday abbreviated
    %b         Month abbreviated name
    %d         Day of the month
    %H         Hour (24-hour format)
    %M         Minute with zero padding
    %S         Second with zero padding
    %z         UTC offset
    %Y         Full year
    

    将字符串日期转换为datetime 对象后,您可以使用strftime 函数将其转换回指定格式的字符串。您可以阅读有关格式的更多信息here

    最后,只需修改Datetime

    df['Datetime'] = df['Datetime'].apply(modify_datetime)
    

    【讨论】:

      【解决方案2】:

      您可以适当地使用pandas.<strong>to_datetime</strong>pandas.Series.dt.<strong>strftime</strong>

      >>> import pandas as pd
      >>> from datetime import datetime
      >>> datetime_strs = ["Thu Jun 18 23:04:19 +0000 2020", "Thu Jun 18 23:04:18 +0000 2020", "Thu Jun 18 23:04:14 +0000 2020", "Thu Jun 18 23:04:13 +0000 2020"]
      >>> d = {'Datetimes': datetime_strs}
      >>> df = pd.DataFrame(data=d)
      >>> df
                              Datetimes
      0  Thu Jun 18 23:04:19 +0000 2020
      1  Thu Jun 18 23:04:18 +0000 2020
      2  Thu Jun 18 23:04:14 +0000 2020
      3  Thu Jun 18 23:04:13 +0000 2020
      >>> df['Datetimes'] = pd.to_datetime(df['Datetimes'], format='%a %b %d %H:%M:%S %z %Y')
      >>> df
                        Datetimes
      0 2020-06-18 23:04:19+00:00
      1 2020-06-18 23:04:18+00:00
      2 2020-06-18 23:04:14+00:00
      3 2020-06-18 23:04:13+00:00
      >>> df['Datetimes'] = df['Datetimes'].dt.strftime('%Y-%m-%d %H:%M:%S')
      >>> df
                   Datetimes
      0  2020-06-18 23:04:19
      1  2020-06-18 23:04:18
      2  2020-06-18 23:04:14
      3  2020-06-18 23:04:13
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 2020-08-23
        • 2013-06-29
        • 2017-05-13
        • 2015-08-04
        • 1970-01-01
        相关资源
        最近更新 更多