2024-08-23|閱讀時間 ‧ 約 21 分鐘

如何調整成Python的日期格式

首先我們可用pandas的to_datetime函數:

import pandas as pd

data["一般日期_python格式"] = pd.to_datetime(data["一般日期"])
raw-image

如果是中文日期的話,我們可以這麼做

for i,j in zip(["年","月","日"],["/","/",""]):
data["中文日期"] = list(map(lambda x: x.replace(i,j),data["中文日期"]))

data["中文日期_python格式"] = pd.to_datetime(data["中文日期"])


另外,我們可用datetime模組的date()函數做同樣的事情:

data["一般日期_python格式"] = list(map(lambda x: datetime.date(year = int(x.split("/")[0]),
month = int(x.split("/")[1]),
day = int(x.split("/")[2])),data["一般日期"]))

同樣的也可以轉換中文日期

for i,j in zip(["年","月","日"],["/","/",""]):
data["中文日期"] = list(map(lambda x: x.replace(i,j),data["中文日期"]))

data["中文日期_python格式"] = list(map(lambda x: datetime.date(year = int(x.split("/")[0]),
month = int(x.split("/")[1]),
day = int(x.split("/")[2])),
data["中文日期"]))

如果是「日期時間」格式,也可以用datetime模組的datetime()函數來做轉換

data["日期部分"] = list(map(lambda x: x.split(" ")[0] ,data["日期時間"]))

for i,j in zip(["年","月","日"],[0,1,2]):
data[i] = list(map(lambda x: x.split("/")[j],data["日期部分"]))

data["時間部分"] = list(map(lambda x: x.split(" ")[1] ,data["日期時間"]))

for i,j in zip(["時","分","秒"],[0,1,2]):
data[i] = list(map(lambda x: x.split(":")[j],data["時間部分"]))

data["日期時間_彙整"] = data["年"] + "/" + data["月"]+ "/" + data["日"]+ "/" + data["時"]+ "/" + data["分"]+ "/" + data["秒"]

data["日期時間_python格式"] = list(map(lambda x: datetime.datetime(year = int(x.split("/")[0]),
month = int(x.split("/")[1]),
day = int(x.split("/")[2]),
hour = int(x.split("/")[3]),
minute = int(x.split("/")[4]),
second = int(x.split("/")[5]))
,data["日期時間_彙整"]))



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.