将格式为1st,2nd..nthMonthYYYY的日期字符串转换为python date obj

2024-04-19 23:13:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我转换日期字符串吗

  • 1998年10月1日
  • 1998年10月2日
  • 1998年10月3日
  • 1998年10月4日

我在datetime.strptime() behaviour中看不出它允许这种格式。你知道吗


Tags: 字符串datetime格式behaviourstrptime
3条回答

显然我在回答你的问题时犯了个错误。

要在不使用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()转换它。你知道吗


在数据帧中,我们可以通过使用本机函数来实现。假设DataFrame是df,date string format列是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()转换列。你知道吗

您仍然可以使用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

import dateutil.parser

s = "1st-October-1998"
d = dateutil.parser.parse(s)
print(d.date())

输出:

1998-10-01

相关问题 更多 >