【问题标题】:How to modify Datetime index format (UTC) in Pandas?如何修改 Pandas 中的日期时间索引格式(UTC)?
【发布时间】:2015-03-30 01:41:47
【问题描述】:

我有一个看起来像这样的 df:

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  

如何删除 -05:00 使其看起来像这样?:

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  

澄清一下,时间没问题,我不需要对此做任何转换,修改的只是格式,(-05:00)

更新:

为了更清楚。 -5:00 来自应用此程序

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

谢谢

【问题讨论】:

  • 你想在什么样的输出中格式化呢?只是在控制台输出中,还是在其他地方?
  • @joris 就在控制台输出中。谢谢
  • 您当然可以使用.tz_localize(None) 删除时区,但这会改变实际值。此外,我不知道如何更改日期在输出中的格式
  • 试试这个!它'dateStr = str(df) dt = datetime.datetime.strptime(dateStr.split(" ")[0], "%Y-%m-%d %H:%M:%S") retDate = dt. strftime('%Y/%m/%d %H:%M:%S')'
  • @Java.beginner 你确定 datetime.datetime 吗?

标签: python datetime pandas time-series


【解决方案1】:

这是 2015 年 1 月的一个老问题。但是由于还没有答案(尽管有很多 cmets),所以这里是 2019 年 10 月的答案。最初的提问者可能已经找到了答案,但只是作为未来的参考.

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2020-06-02
    • 2016-03-15
    • 2019-07-27
    • 2023-03-23
    相关资源
    最近更新 更多