我有一個帶有日期值的 Pandas 資料框,但是,我需要將它從日期轉換為文本通用格式,如 Excel,而不是日期字串,以便與 SQL 中的主鍵值匹配,不幸的是,這些值通常重新排序格式。是否可以使用 Python 或唯一的方法將此列轉換為 Excel 中的常規格式?
這是資料框的列的樣子:
ID Desired Output
1/1/2022 44562
7/21/2024 45494
1/1/1931 11324
uj5u.com熱心網友回復:
是的,這是可能的。Excel 中的一般格式從日期 1900-1-1 開始計算天數。
您可以計算 ID 和 1900-1-1 中的日期之間的時間差。
受這篇文章的啟發,你可以做...
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
plus 2 試圖處理閏年。對于您提供的日期 2 似乎是正確的,但您應該驗證這一點。
編輯
僅根據MrFuppes 的建議使用熊貓
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)
我猜大熊貓正在處理閏年?
uj5u.com熱心網友回復:
Excel 將日期存盤為連續的序列號,以便它們可以用于計算。默認情況下,1900 年 1 月 1 日是序列號 1,而 2008 年 1 月 1 日是序列號 39448,因為它是 1900 年 1 月 1 日之后的 39,447 天。-
Microsoft 的檔案
所以你可以計算 (difference between your date and January 1, 1900) 1
請參閱如何計算兩個給定日期之間的天數
uj5u.com熱心網友回復:
首先,確定資料型別。然后,您將有更多的作業要做。您可以使用 '.astype()' 來更改資料的型別,使用迭代器來洗掉 '/' 標記,或使用其他方法來更改它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399206.html
上一篇:如何以角度獲取當前日期為2021-12-30T18:30:00.000z這種格式
下一篇:在Room中選擇當天的任務
