【发布时间】:2019-09-19 22:33:03
【问题描述】:
我正在寻找一种将 pandas 时间戳更改为 python 日期时间对象的方法,但我失败了。我用过 to_pydatetime()。
下面是我的 cmets 代码:
import pandas
import datetime
import pytz
forced_UTC = pytz.timezone("Europe/London").localize(datetime.datetime(2019, 1, 30, 9, 5)).tzinfo
forced_BST = pytz.timezone("Europe/London").localize(datetime.datetime(2019, 4, 27, 9, 5)).tzinfo
#print (forced_UTC, forced_BST)
# Create dataframe and check the value of the first element in the column.
my_df = pandas.DataFrame({"my_column": ["2019-04-01 00:15:00", "2019-02-23 13:00:00", "2019-02-23 14:00:00"]})
first_date = my_df["my_column"].iloc[0]
print (first_date, type(first_date)) # 2019-04-01 00:15:00 <class 'str'>
# Change every element in the column from string to datetime object.
my_df["my_column"] = [datetime.datetime.strptime(element, "%Y-%m-%d %H:%M:%S").replace(tzinfo=forced_UTC) for element in my_df["my_column"]]
first_date = my_df["my_column"].iloc[0]
print (first_date, type(first_date)) # <class 'pandas._libs.tslibs.timestamps.Timestamp'>
# Didn't work, thought it would make them python datetime objects.
# Try creating a new list and replacing the column.
list_to_replace = [element.to_pydatetime() for element in my_df["my_column"]] # make all timestamps datetimes
print (list_to_replace[0],type(list_to_replace[0])) # 2019-04-01 01:15:00+01:00 <class 'datetime.datetime'>
my_df["my_column"] = [element for element in list_to_replace]
first_date = my_df["my_column"].iloc[0]
print (first_date, type(first_date))# 2019-04-01 01:15:00+01:00 <class pandas._libs.tslibs.timestamps.Timestamp'>
# Didn't work.
# Use to_pydatetime() doesn't work either
print (first_date.to_pydatetime(), type(first_date)) # 2019-04-01 01:15:00+01:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
# Using to_pydatetime() like this works!?!?!?!
first_date = my_df["my_column"].iloc[0].to_pydatetime()
print (first_date, type(first_date)) # 2019-04-01 01:15:00+01:00 <class 'datetime.datetime'>
# print (datetime.datetime.strftime(first_date, "%H"))
# print (datetime.datetime(2019, 4, 1, 0, 15, tzinfo=forced_BST) > first_date)
谁能看出我做错了什么?
【问题讨论】:
-
我发现 cmets 很难跟上。我想他们说当你打电话给
to_pydatetime()时,你会得到你想要的,所以我不清楚你在问什么。 -
当我为 1 个元素执行此操作时它可以工作,但是当我为所有元素调用该函数并尝试替换数据框的列时它会失败。
标签: python pandas datetime timestamp pytz