Python 更改日期时间格式(包括工作日)?

Python 更改日期时间格式(包括工作日)?,python,pandas,date,datetime,timestamp,Python,Pandas,Date,Datetime,Timestamp,目前我有此格式的datetime列 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:

目前我有此格式的datetime列

        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
您可以使用并适当地:

>>> 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

假设已加载数据帧,则可以使用此函数将
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')
strtime
函数的第一个参数是日期字符串,第二个参数是格式

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
函数将其转换回指定格式的字符串。您可以阅读有关格式的更多信息

最后,只需修改
Datetime

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