python 中的日期时间格式与格式不同
Datetime format in python is not as same as format
我的数据框中有一个日期,格式如下
"2018-05-01"
"2018-05-02"
"2018-05-03"
我想在 JSON
中将日期转换成类似这样的内容
"2018-05-01T00:00:00.000Z"
"2018-05-02T00:00:00.000Z"
我曾尝试使用 pd.to_datetime(df['date'])
但结果在我的 JSON 文件中变成了 1523404800000
之类的东西。我应该怎么做才能在我的 JSON 中获得类似 "2018-05-02T00:00:00.000Z"
的格式?
您正在 df.to_json()
寻找 date_format='iso'
完整示例:
import pandas as pd
csvdata = '''\
date
2018-05-01
2018-05-02
2018-05-03'''
fileobj = pd.compat.StringIO(csvdata)
df = pd.read_csv(fileobj, sep='\s+')
# without conversion
print(df.to_json())
# with conversion
df['date'] = pd.to_datetime(df['date'])
print(df.to_json())
# with conversion and adding date_format = iso
print(df.to_json(date_format='iso'))
打印:
{"date":{"0":"2018-05-01","1":"2018-05-02","2":"2018-05-03"}}
{"date":{"0":1525132800000,"1":1525219200000,"2":1525305600000}}
{"date":{"0":"2018-05-01T00:00:00.000Z","1":"2018-05-02T00:00:00.000Z","2":"2018-05-03T00:00:00.000Z"}}
我的数据框中有一个日期,格式如下
"2018-05-01"
"2018-05-02"
"2018-05-03"
我想在 JSON
中将日期转换成类似这样的内容"2018-05-01T00:00:00.000Z"
"2018-05-02T00:00:00.000Z"
我曾尝试使用 pd.to_datetime(df['date'])
但结果在我的 JSON 文件中变成了 1523404800000
之类的东西。我应该怎么做才能在我的 JSON 中获得类似 "2018-05-02T00:00:00.000Z"
的格式?
您正在 df.to_json()
date_format='iso'
完整示例:
import pandas as pd
csvdata = '''\
date
2018-05-01
2018-05-02
2018-05-03'''
fileobj = pd.compat.StringIO(csvdata)
df = pd.read_csv(fileobj, sep='\s+')
# without conversion
print(df.to_json())
# with conversion
df['date'] = pd.to_datetime(df['date'])
print(df.to_json())
# with conversion and adding date_format = iso
print(df.to_json(date_format='iso'))
打印:
{"date":{"0":"2018-05-01","1":"2018-05-02","2":"2018-05-03"}}
{"date":{"0":1525132800000,"1":1525219200000,"2":1525305600000}}
{"date":{"0":"2018-05-01T00:00:00.000Z","1":"2018-05-02T00:00:00.000Z","2":"2018-05-03T00:00:00.000Z"}}