Как изменить временные метки панд на объекты даты и времени Python? - PullRequest
0 голосов
/ 01 мая 2019

Я ищу способ изменить временные метки панд на объекты даты и времени Python, и мне не удается. Я использовал to_pydatetime ().

Ниже мой код с комментариями:

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)

Кто-нибудь может увидеть, что я делаю не так?

1 Ответ

0 голосов
/ 01 мая 2019

Это работает, но вы печатали type без изменения типа.
Здесь вы действительно печатаете дату панды (first_date) и тип панды (type(first_date)).

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.

В этом случае вы печатаете дату Python (first_date.to_pydatetime()), поскольку вы действительно используете to_pydatetime, но переменная first_date никогда не изменялась, поэтому type по-прежнемудата панды.

print (first_date.to_pydatetime(), type(first_date)) # 2019-04-01 01:15:00+01:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>

И здесь вы также перезаписываете first_date переменную с датой Python (first_date = first_date.to_pydatetime()), поэтому вы считаете, что она работает только тогда,Так что теперь first_date будет датой Python, а type(first_date) будет, следовательно, возвращать то, что вы ожидали

# 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'>
...