是的,这是可能的。 Excel 中的一般格式从日期 1900-1-1 开始计算天数。
您可以计算 ID 中的日期与 1900-1-1 之间的时间差。
受到this post 的启发,你可以做...
import pandas as pd
from datetime import date
# create a data frame
data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})
# convert the strings in ID to a datetime, then into a series with squeeze and then to a date format. The date format is helpful when calculating time deltas.
sr = pd.to_datetime(data['ID'], format= '%m/%d/%Y').squeeze().dt.date
# Calculate the time deltas by subtracting 1900-1-1 from date in sr and store it in the General format column of data.
data['General format'] = sr.apply(lambda x: (x - date(1900, 1, 1)).days +2 ).to_frame()
print(data)
ID General format
0 1/1/2022 44562
1 7/21/2024 45494
2 1/1/1931 11324
这里有点不简洁...
import pandas as pd
from datetime import date
data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})
ID_to_datetime = pd.to_datetime(data['ID'], format= '%m/%d/%Y')
ID_to_datetime_to_series = ID_to_datetime.squeeze()
ID_to_datetime_to_series_to_date = ID_to_datetime_to_series.dt.date
General_format = []
for a_date in ID_to_datetime_to_series_to_date:
timedelta = a_date - date(1900, 1, 1)
General_format.append(timedelta.days + 2 )
data['General format'] = General_format
print(data)
ID General format
0 1/1/2022 44562
1 7/21/2024 45494
2 1/1/1931 11324
加 2 试图处理闰年。对于您提供的日期,+2 似乎是正确的,但您应该验证这一点。
编辑
仅根据 MrFuppes 的建议使用 pandas
data = pd.DataFrame({'ID': ['1/1/2022','7/21/2024','1/1/1931']})
data['General format'] = (pd.to_datetime(data["ID"])-pd.Timestamp("1899-12-30")).dt.days
print(data)
我猜熊猫正在处理闰年?