Mau*_*ice 15 python datetime pandas
我正在处理 pandas 中的日期时间信息,并希望将一堆datetime64[ns]列转换为str. 我注意到这两种方法的行为有所不同,我预计会产生相同的结果。
这是一个MCVE。
import pandas as pd
# Create a dataframe with dates according to ISO8601
df = pd.DataFrame({"dt_column": ["2023-01-01", "2023-01-02", "2023-01-02"]})
# Convert the strings to datetimes
# (I expect the time portion to be 00:00:00)
df["dt_column"] = pd.to_datetime(df["dt_column"])
df["str_from_astype"] = df["dt_column"].astype(str)
df["str_from_apply"] = df["dt_column"].apply(str)
print(df)
print()
print("Datatypes of the dataframe")
print(df.dtypes)
Run Code Online (Sandbox Code Playgroud)
输出
dt_column str_from_astype str_from_apply
0 2023-01-01 2023-01-01 2023-01-01 00:00:00
1 2023-01-02 2023-01-02 2023-01-02 00:00:00
2 2023-01-02 2023-01-02 2023-01-02 00:00:00
Datatypes of the dataframe
dt_column datetime64[ns]
str_from_astype object
str_from_apply object
dtype: object
Run Code Online (Sandbox Code Playgroud)
如果我使用.astype(str)时间信息就会丢失,而当我使用.apply(str)时间信息时会保留(或推断)。
这是为什么?
(熊猫 v1.5.2、Python 3.9.15)
moz*_*way 18
时间信息永远不会丢失,如果您使用2023-01-02 12:00,您会看到所有时间都将出现在 中astype,但在原始日期时间列中也可见:
dt_column str_from_astype str_from_apply
0 2023-01-01 00:00:00 2023-01-01 00:00:00 2023-01-01 00:00:00
1 2023-01-02 00:00:00 2023-01-02 00:00:00 2023-01-02 00:00:00
2 2023-01-02 12:00:00 2023-01-02 12:00:00 2023-01-02 12:00:00
Run Code Online (Sandbox Code Playgroud)
使用apply,pythonstr内置函数应用于每个Timestamp对象,它始终显示完整格式:
str(pd.Timestamp('2023-01-01'))
# '2023-01-01 00:00:00'
Run Code Online (Sandbox Code Playgroud)
使用 时astype,格式由 处理pandas.io.formats.format.SeriesFormatter,它更智能一些,并根据上下文决定输出格式(这里是系列中的其他值以及非空时间的存在)。
无论如何,明确的规范方法是使用dt.strftime:
# without time
df["dt_column"].dt.strftime('%Y-%m-%d')
# with time
df["dt_column"].dt.strftime('%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)