[英]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",
json
library to solve the issue.
01/22/2012
, /
就會用\
轉義。'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.