Search code examples
pythonpandasdatetimepython-datetime

DataTimeIndex to ISO 8601 string


I have a pandas dataframe t whose index (in the form of a datetime64 object) I want to convert to an ISO 8601 string.

t.index

DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 01:00:00',
               '2011-01-01 02:00:00', '2011-01-01 03:00:00',
               '2011-01-01 04:00:00'],
              dtype='datetime64[ns]', name='datetime', freq=None)

When I convert the index to a series and then use .dt to access the datetimelike properties of the series, I am left with a datetime object that contains both formats:

times = times.to_series().dt.strftime('%Y-%m-%dT%H:%M%:%SZ')
print(str(times))

datetime
2011-01-01 00:00:00    2011-01-01T00:00:00Z
2011-01-01 01:00:00    2011-01-01T01:00:00Z
2011-01-01 02:00:00    2011-01-01T02:00:00Z
2011-01-01 03:00:00    2011-01-01T03:00:00Z
2011-01-01 04:00:00    2011-01-01T04:00:00Z
Name: datetime, dtype: object

Why does this return two different formats side by side? How does one only return a string in the second (ISO 8601) format?


Solution

  • When you do to_series, it will copy the index into values and create the series which also carry over the origina index.

    times = times.to_series()
    print(str(times))
    
    datetime
    2011-01-01 00:00:00    2011-01-01 00:00:00
    2011-01-01 01:00:00    2011-01-01 01:00:00
    2011-01-01 02:00:00    2011-01-01 02:00:00
    2011-01-01 03:00:00    2011-01-01 03:00:00