python-3.x - 更改python数据框中的日期时间格式
问题描述
我有以下 csv 文件并且我在使用 python pandas 作为数据框时打开了。我需要将文件修改如下: 1 - 将列(本地时间)重命名为日期 2 - 从列(日期)中删除除日期本身之外的任何内容(例如 2.6.2019) 3- 将日期格式更改为 mm/dd/ yyyy 4 - 将新文件导出为 csv 谢谢
解决方案
使用pd.to_datetime时要传递的关键参数是dayfirst=True。然后,使用.dt.strftime('%m/%d/%Y')更改为所需的格式。我还为您提供了一个如何重命名列和读取/写入 .csv 的示例。再一次,我知道你在移动,但下一次,我会表现出更多的努力。
import pandas as pd
# df=pd.read_csv('filename.csv')
# I have manually created a dataframe below, but the above is how you read in a file.
df=pd.DataFrame({'Local time' : ['11.02.2015 00:00:00.000 GMT+0200',
'12.02.2015 00:00:00.000 GMT+0200',
'15.03.2015 00:00:00.000 GMT+0200']})
#Converting string to datetime and changing to desired format
df['Local time'] = pd.to_datetime(df['Local time'],
dayfirst=True).dt.strftime('%m/%d/%Y')
#Example to rename columns
df.rename(columns={'Local time' : 'Date'}, inplace=True)
df.to_csv('filename.csv', index=False)
df
推荐阅读
- c++ - 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- appium - Appium 桌面 - 找不到“adb”
- ios - 访问 cellForRowAt indexPath 之外的 UITableViewCell 的行号
- elasticsearch - 有没有办法使用 Elasticsearch 找到最不相似的记录(或“更多不同”)
- c# - 如何使用 Microsoft Graph 查询参数查询生日月份和年份?
- oauth-2.0 - Nodemailer 和 Oauth2——未处理的承诺拒绝错误
- csv - 如何在vi中转义&字符
- azure-sql-database - 将 DATETIME2 列与 DATETIME2 字段进行比较不会返回预期结果
- c++ - 使用 OpenSSL (DTLS) 避免零碎的 ClientHello
- javascript - 在某些反应时删除嵌入