Pandas,将日期时间格式从mm/dd/yyyy转换为dd/mm/yyyy

11
默认的csv格式为dd/mm/yyyy。当我使用 df['Date']=pd.to_datetime(df['Date']) 进行转换时,它会将其格式更改为mm/dd/yyyy。
然后,我使用了 df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%m/%Y') 来将其转换为dd/mm/yyyy格式,但是它们仍然是字符串(object)格式。然而,我需要将它们转换为datetime格式。当我再次使用这个命令 (df['Date']=pd.to_datetime(df['Date'])) 时,它又回到了以前的格式。需要您的帮助。

不,如果想要日期时间对象,在Python中是不可能的。 - jezrael
那么,如果我想要新的格式,该如何解决这个问题? - Amn Kh
你尝试过使用pd.to_datetimeformat参数吗? - Mohit Motwani
@MohitMotwani,是的,但没有区别。 - Amn Kh
3个回答

15
您可以使用pd.read_csvparse_datesdayfirst参数,详情请参见:read_csv()文档
df = pd.read_csv('myfile.csv', parse_dates=['Date'], dayfirst=True)

这将把Date列读取为日期时间值,正确地将日期输入的第一部分作为日期。请注意,通常您希望将日期存储为日期时间对象。

然后,如果您需要将日期输出为字符串,可以调用dt.strftime()

df['Date'].dt.strftime('%d/%m/%Y')

1
不行,这个不起作用 - 哎呀,Python 真让人沮丧。 - GenDemo
如果您的文件日期格式为mm/dd/yy,则将dayfirst设置为False。 - Alaike3

1
当我再次使用df['Date'] = pd.to_datetime(df['Date'])时,它会恢复到以前的格式。
不,您不能同时拥有所选字符串格式和保持datetime类型的系列。正如此处所述:

datetime series are stored internally as integers. Any human-readable date representation is just that, a representation, not the underlying integer. To access your custom formatting, you can use methods available in Pandas. You can even store such a text representation in a pd.Series variable:

formatted_dates = df['datetime'].dt.strftime('%m/%d/%Y')

The dtype of formatted_dates will be object, which indicates that the elements of your series point to arbitrary Python times. In this case, those arbitrary types happen to be all strings.

Lastly, I strongly recommend you do not convert a datetime series to strings until the very last step in your workflow. This is because as soon as you do so, you will no longer be able to use efficient, vectorised operations on such a series.


1

这个解决方案适用于所有包含混合日期格式的列。如果需要,可以向函数添加更多条件。Pandas to_datetime() 函数对我来说不起作用,但这个方法似乎很好用。

import date
def format(val):
    a = pd.to_datetime(val, errors='coerce', cache=False).strftime('%m/%d/%Y')
    try:
        date_time_obj = datetime.datetime.strptime(a, '%d/%m/%Y')
    except:
        date_time_obj = datetime.datetime.strptime(a, '%m/%d/%Y')
    return date_time_obj.date()

将更改保存到同一列。
df['Date'] = df['Date'].apply(lambda x: format(x))

保存为CSV格式。
df.to_csv(f'{file_name}.csv', index=False, date_format='%s')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接