2024-04-19 23:13:25 发布
网友
有人能帮我转换日期字符串吗
我在datetime.strptime() behaviour中看不出它允许这种格式。你知道吗
显然我在回答你的问题时犯了个错误。
要在不使用regex的情况下将字符串转换为日期,我们可以尝试
from datetime import datetime as dt s = '22nd-October-1998' dt.strptime(s.replace(s[s.find('-')-2:s.find('-')], ''), '%d-%B-%Y').date()
其思想是找到字符-,然后用空字符串替换-之前的2个字符,然后使用datetime.strptime()转换它。你知道吗
-
datetime.strptime()
在数据帧中,我们可以通过使用本机函数来实现。假设DataFrame是df,date string format列是Date,那么我们可以使用
df
Date
pd.to_datetime(df['Date'].replace(dict.fromkeys(['st', 'nd', 'rd', 'th'], ''), regex=True), format='%d-%B-%Y')
其思想是用空字符串替换子字符串['st', 'nd', 'rd', 'th'],然后使用pandas.to_datetime()转换列。你知道吗
['st', 'nd', 'rd', 'th']
您仍然可以使用strtime,但是需要使用regex删除数据中的额外字符
import re date_string = "1st-October-1998" def remove_extra_chars(ds): return re.sub(r'(\d)(st|nd|rd|th)', r'\1', ds) d = datetime.strptime(solve(date_string), '%d-%B-%Y') print(d.strftime('%d-%B-%Y')) # output: 01-October-1998 print(d.strftime('%Y-%m-%d')) # output: 1998-10-01
您可以尝试使用dateutil.pareser:
dateutil.pareser
import dateutil.parser s = "1st-October-1998" d = dateutil.parser.parse(s) print(d.date())
输出:
1998-10-01
显然我在回答你的问题时犯了个错误。
要在不使用regex的情况下将字符串转换为日期,我们可以尝试
其思想是找到字符
-
,然后用空字符串替换-
之前的2个字符,然后使用datetime.strptime()
转换它。你知道吗在数据帧中,我们可以通过使用本机函数来实现。假设DataFrame是
df
,date string format列是Date
,那么我们可以使用其思想是用空字符串替换子字符串
['st', 'nd', 'rd', 'th']
,然后使用pandas.to_datetime()转换列。你知道吗您仍然可以使用strtime,但是需要使用regex删除数据中的额外字符
您可以尝试使用
dateutil.pareser
:输出:
相关问题 更多 >
编程相关推荐