我可以使用Python将浮点数转换为日期时间吗?

问题描述 投票:0回答:1

我有一个数据类型为 float 的日期列,我可以获得有关如何转换为 datetime64 的帮助

这就是我尝试过的 newdf["Year_Sold"] = pd.to_datetime(df["Year_Sold"]) n Year_sold 是一列,所有值的数据类型均为 float,但我希望数据类型为 datetime64

python time types datetime-format
1个回答
0
投票

要将浮点数据类型的列转换为 pandas 中的

datetime64
,通常需要确保浮点值代表有效日期。由于您正在处理名为
"Year_Sold"
的列,我假设 这些浮点数代表年份,可能还带有一些额外的十进制表示形式,以便在一年内更精确地计时。您的代码的问题是
pd.to_datetime
期望输入采用某种日期格式,例如
"YYYY-MM-DD"
"DD/MM/YYYY"
等用于日期或类似的时间戳。 换句话说,如果您尝试向其中添加代表年份的浮点值,它不会知道这些数字是否代表年、日、月,或者年+日期+数字的其他组合,例如写为
"2024-01-01"
"20240101.0"
.

因此,考虑到我上面解释的关于

"Year_Sold"
列的含义的两个可能的假设,对于任何一种情况,以下是实现最终结果的方法:

选项 1:如果
"Year_Sold"
将年份表示为浮点数

如果您的

"Year_Sold"
列仅包含年份作为
float
,您可以首先将这些浮点数转换为整数,然后再转换为字符串。由于日期不仅包含年份信息,还包含月份和日期,因此您需要添加标准月份和日期以使其成为完整的日期字符串。然后,您可以使用
pd.to_datetime
将这些字符串转换为
datetime64
类型值。

以下是转换色谱柱所需步骤的摘要:

  1. float
    值转换为
    integers
    (删除小数部分,假设它仅代表年份)。
  2. 将这些整数转换为字符串,并向其附加标准日期(例如,
    "-01-01"
    表示 1 月 1 日)以形成完整的日期字符串。
  3. 使用
    pd.to_datetime
    将这些
    strings
    转换为
    datetime64
    格式。

这是实现:

import pandas as pd

# Sample DataFrame creation with float years
df = pd.DataFrame({'Year_Sold': [2020.0, 2021.5, 2022.0]})
# df looks like this:
#
#    Year_Sold
# 0     2020.0
# 1     2021.5
# 2     2022.0

# Step 1 & 2: Convert floats to strings representing full dates (assuming "-01-01" for simplicity)
df['Year_Sold'] = df['Year_Sold'].apply(lambda x: str(int(x)) + "-01-01")

# Step 3: Convert the string dates to datetime64
df['Year_Sold'] = pd.to_datetime(df['Year_Sold'])

print(df)
# Prints:
#
#    Year_Sold
# 0 2020-01-01
# 1 2021-01-01
# 2 2022-01-01

选项 2:如果
"Year_Sold"
包含小数以获得更精确的计时

如果

"Year_Sold"
列表示带有附加十进制表示形式的年份,以便在一年内实现更精确的计时,则您需要采用更细致的方法将这些
floats
转换为
datetime
对象。 小数部分可以代表年份的一小部分,需要转换成对应的月份和日期。这有点复杂,因为:

  1. 您需要确定一年的小数部分对应多少天。由于不同年份的天数不同(闰年为 365 或 366),因此计算结果会因年份而略有不同。
  2. 计算出小数部分代表的天数后,您将这些天数添加到年初以获得精确的日期。

以下是解决此问题的方法:

  1. 将浮点数的年份部分转换为整数(这代表年份)。
  2. 将小数部分乘以该年的天数,即可得到该年的天数分数。
  3. 将这些天添加到年初以获得准确的日期时间。

让我们用 Python 来实现这个:

import pandas as pd
from datetime import datetime, timedelta

def float_year_to_datetime(year_float):
    year = int(year_float)
    remainder = year_float - year
    start_of_year = datetime(year, 1, 1)
    days_in_year = 366 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 365
    days_from_fraction = round(remainder * days_in_year)
    return start_of_year + timedelta(days=days_from_fraction)


# Example DataFrame
df = pd.DataFrame({'Year_Sold': [2020.25, 2021.5, 2022.75, 2022.98,
                                 2022.99, 2022.995, 2022.996, 2022.999]})
# df looks like this:
#
#    Year_Sold
# 0   2020.250
# 1   2021.500
# 2   2022.750
# 3   2022.980
# 4   2022.990
# 5   2022.995
# 6   2022.996
# 7   2022.999

# Convert the float years to datetime
df['Year_Sold'] = df['Year_Sold'].apply(float_year_to_datetime)
print(df)
# Prints:
#
#    Year_Sold
# 0 2020-04-02
# 1 2021-07-02
# 2 2022-10-02
# 3 2022-12-25
# 4 2022-12-28
# 5 2022-12-30
# 6 2022-12-31
# 7 2023-01-01

此函数

float_year_to_datetime
执行以下操作:

  • 它分隔年份和小数部分。
  • 它将一年的开始计算为
    datetime
    对象。
  • 它确定一年中有多少天来计算闰年。
  • 它将小数部分转换为天数,并将这些天数添加到年初。
© www.soinside.com 2019 - 2024. All rights reserved.