pandas 熊猫以 ISO 格式保存日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28729212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:59:08  来源:igfitidea点击:

pandas save date in ISO format?

pythondatetimepandas

提问by Borisw37

I'm trying to generate a Pandas DataFrame where date_range is an index. Then save it to a CSV file so that the dates are written in ISO-8601 format.

我正在尝试生成一个 Pandas DataFrame,其中 date_range 是一个索引。然后将其保存为 CSV 文件,以便以 ISO-8601 格式写入日期。

import pandas as pd
import numpy as np
from pandas import DataFrame, Series

NumberOfSamples = 10
dates = pd.date_range('20130101',periods=NumberOfSamples,freq='90S')
df3 = DataFrame(index=dates)
df3.to_csv('dates.txt', header=False)

The current output to dates.txt is:

到dates.txt 的当前输出是:

2013-01-01 00:00:00
2013-01-01 00:01:30
2013-01-01 00:03:00
2013-01-01 00:04:30
...................

I'm trying to get it to look like:

我试图让它看起来像:

2013-01-01T00:00:00Z
2013-01-01T00:01:30Z
2013-01-01T00:03:00Z
2013-01-01T00:04:30Z
....................

回答by EdChum

Use datetime.strftimeand call mapon the index:

使用datetime.strftime和调用map索引:

In [72]:

NumberOfSamples = 10
import datetime as dt
dates = pd.date_range('20130101',periods=NumberOfSamples,freq='90S')
df3 = pd.DataFrame(index=dates)
df3.index = df3.index.map(lambda x: dt.datetime.strftime(x, '%Y-%m-%dT%H:%M:%SZ'))
df3
Out[72]:
Empty DataFrame
Columns: []
Index: [2013-01-01T00:00:00Z, 2013-01-01T00:01:30Z, 2013-01-01T00:03:00Z, 2013-01-01T00:04:30Z, 2013-01-01T00:06:00Z, 2013-01-01T00:07:30Z, 2013-01-01T00:09:00Z, 2013-01-01T00:10:30Z, 2013-01-01T00:12:00Z, 2013-01-01T00:13:30Z]

Alternatively and better in my view (thanks to @unutbu) you can pass a format specifier to to_csv:

或者,在我看来更好(感谢@unutbu)您可以将格式说明符传递给to_csv

df3.to_csv('dates.txt', header=False, date_format='%Y-%m-%dT%H:%M:%SZ')