简体   繁体   中英

How to modify Datetime index format (UTC) in Pandas?

I have a df that looks like this:

2015-01-29 08:30:00-05:00  199425  199950  199375  199825                  
2015-01-29 08:45:00-05:00  199825  199850  199650  199800                 
2015-01-29 09:00:00-05:00  199825  199900  199450  199625  

How can I remove the -05:00 so It looks like this?:

2015-01-29 08:30:00  199425  199950  199375  199825                  
2015-01-29 08:45:00  199825  199850  199650  199800                 
2015-01-29 09:00:00  199825  199900  199450  199625  

Just to clarify, the time is fine, I don't need to do any transformation on that, the modification is just the format, (-05:00)

Update:

For further clarity. The -5:00 comes out of applying this procedure

eastern = pytz.timezone('US/Eastern')
df.index = df.index.tz_localize(pytz.utc).tz_convert(eastern)

Thanks

This is an old question from Jan 2015. But since there is no answer yet (although lots of comments), here is an answer in Oct 2019. The original questioner probably found an answer already but just as a reference for the future.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

import pandas as pd

# create dataframe
df = pd.DataFrame({
    'date_original': ['2015-01-29 08:30:00-05:00', '2015-01-29 08:45:00-05:00', '2015-01-29 09:00:00-05:00'],
    'measurement': [199425, 199825, 199825]
})

# make sure to convert date column to datetime, not string
df['date_original'] = pd.to_datetime(df['date_original'])

print('Original dataframe:')
print(df)
print()

# remove the suffix from the date
df['date_transform'] = pd.to_datetime(df['date_original']).dt.strftime('%Y-%m-%d %H:%M:%S')

print('Transformed dataframe:')
print(df)
print()
df

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM