【问题标题】:Using index=False in df.to_csv change the datetime format from '%m/%d/%Y' to '%m-%d-%Y'在 df.to_csv 中使用 index=False 将日期时间格式从 '%m/%d/%Y' 更改为 '%m-%d-%Y'
【发布时间】:2020-06-22 02:27:20
【问题描述】:

我为白天生成一个 '%m/%d/%Y' 格式的 CSV 文件,并使用

将其保存为 CSV

df.to_csv 命令;但是,此方法会将行索引添加为第一列。为了避免这种情况,我将 index=False 添加为 df.to_csv 命令的参数。但是,由于我无法弄清楚这会将时间列更改为“%m-%d-%Y”的原因。谁能告诉我为什么会发生这种情况以及如何防止这种情况发生?

 df.to_csv(Path)              # retains the datetime foremat

 df.to_csv(Path, index=False) # Change the datetime format

.

【问题讨论】:

标签: python pandas csv datetime


【解决方案1】:

使用to_csv方法的date_format参数:

df.to_csv("/home/path/file.csv", date_format="%m/%d/%Y", index=False)

如果这还不够,则表示您的列 dtype 不被理解为日期。在这种情况下,你必须强制它。

import pandas as pd

df = pd.DataFrame(
    [{"date": "01/12/2020", "value": 1}, {"date": "31/12/2020", "value": 2}]
)
# date type is not understood, indeed
# the following line will print "object"
# print(df.date.dtype)

# format is the "input" date format
df["date"] = pd.to_datetime(df["date"], format="%d/%m/%Y")

# date_format is the csv output date format
df.to_csv("filename.csv", date_format="%d/%m/%Y", index=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2017-11-02
    • 2023-03-08
    • 2011-02-19
    • 1970-01-01
    • 2022-06-12
    • 2021-03-09
    相关资源
    最近更新 更多