簡體   English   中英

如何正確地將 csv 中包含日期的列轉換為 JSON

[英]How to correctly convert the column in csv that contains the dates into JSON

在我的 csv 文件中, "ESTABLİSHMENT DATE"列由如下斜線分隔: 01/22/2012

I am converting the csv format into the JSON format, which needs to be done with pandas, but the "ESTABLİSHMENT DATE" column isn't correctly translated to JSON.

df = pd.read_csv(my_csv)
df.to_json("some_path", orient="records")

我不明白為什么它笨拙地添加了反斜杠。

"ESTABLİSHMENT DATE":"01\/22\/2012",

但是,我需要將結果寫入文件,如下所示:

"ESTABLİSHMENT DATE":"01/22/2012",
  • Forward slash in json file from pandas dataframe answers why it awkwardly adds the backward slashes , and this answer shows how to use the json library to solve the issue.
    • 只要日期格式是01/22/2012/就會用\轉義。
  • 要使用 pandas 將包含日期的 csv 中的列正確轉換為JSON ,可以通過將'date'列轉換為正確的datetime dtype時間,然后使用.to_json來完成。
    • 2012-01-22是正確的日期時間格式,但.to_json會將其轉換為1327190400000 使用pd.to_datetime將正確的格式設置為%Y-%m-%d后,必須將類型設置為string
import pandas as pd

# test dataframe
df = pd.DataFrame({'date': ['01/22/2012']})

# display(df)
         date
0  01/22/2012

# to JSON
print(df.to_json(orient='records'))
[out]: [{"date":"01\/22\/2012"}]

# set the date column to a proper datetime
df.date = pd.to_datetime(df.date, format='%m/%d/%Y')

# display(df)
        date
0 2012-01-22

# to JSON
print(df.to_json(orient='records'))
[out]: [{"date":1327190400000}]

# set the date column type to string
df.date = df.date.astype(str)

# to JSON
print(df.to_json(orient='records'))
[out]: [{"date":"2012-01-22"}]

# as a single line of code
df.date = pd.to_datetime(df.date, format='%m/%d/%Y').astype(str)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM