pandas以ISO格式保存日期?

时间:2015-02-25 20:44:47

标签: python datetime pandas

我正在尝试生成一个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)

date.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
...................

我试图让它看起来像:

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

1 个答案:

答案 0 :(得分:6)

使用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]

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

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