简体   繁体   English

如何使用 pandas 格式化日期?

[英]How do I format date using pandas?

My data 'df' shows data 'Date' as 1970-01-01 00:00:00.019990103 when this is formatted to date_to using pandas.当使用 pandas 将其格式化为 date_to 时,我的数据“df”将数据“日期”显示为 1970-01-01 00:00:00.019990103。 How do I show the date as 01/03/1999?如何将日期显示为 01/03/1999?

consider LoneWanderer's comment for next time and show some of the code that you have tried.下次考虑 LoneWanderer 的评论并展示您尝试过的一些代码。

I would try this:我会试试这个:

from datetime import datetime

now = datetime.now()

print(now.strftime('%d/%m/%Y'))

You can print now to see that is in the same format that you have and after that is formatted to the format required.您现在可以打印以查看与您拥有的格式相同的格式,然后将其格式化为所需的格式。

I see that the actual date is in last 10 chars of your source string.我看到实际日期在源字符串的最后 10 个字符中。

To convert such strings to a Timestamp (ignoring the starting part), run:要将此类字符串转换为时间戳(忽略起始部分),请运行:

df.Date = df.Date.apply(lambda src: pd.to_datetime(src[-8:]))

It is worth to consider to keep this date just as Timestamp , as it simplifies operations on date / time and apply your formatting only in printouts.值得考虑将此日期保留为Timestamp ,因为它简化了日期/时间的操作并仅在打印输出中应用您的格式。

But if you want to have this date as a string in "your" format, in the "original" column, perform the second conversion ( Timestamp to string ):但是,如果您想将此日期作为“您的”格式的字符串,请在“原始”列中执行第二次转换(时间戳字符串):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM