python - 在Python中格式化日期时间时如何匹配str中的任意字符?

标签 python string datetime format match

我想在 Python 中将字符串转换为日期时间。但有一些字符在字符串中是不相关的。

Python Datetime Document

官方文档中没有明确的方法来匹配String中的任意字符。

<小时/>

例如,我有一个字符串 2018-01-01Ajrwoe

我想将此字符串转换为日期时间,如 2018(年)01(月)和 01(日)

该字符串的其余部分无关紧要。

  • 我知道我可以先更改字符串(删除不相关的字符),例如
raw_str = "2018-01-01Ajrwoe"
my_str = raw_str[:10]
strptime(my_str, my_format)
  • 但我只想直接匹配任意字符,例如
raw_str = "2018-01-01Ajrwoe"
strptime(raw_str, my_format)
  • 但是 my_format 怎么样?

提前致谢。

最佳答案

这是一种使用正则表达式来清理字符串的方法:

raw_str = "2018-01-01Ajrwoe"

datetime.datetime.strptime(re.sub('[a-z|A-Z]', '', raw_str), '%Y-%m-%d')

输出:

datetime.datetime(2018, 1, 1, 0, 0)

关于python - 在Python中格式化日期时间时如何匹配str中的任意字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609167/

相关文章:

c - 字符串如何在 C 中工作?

python - Pandas groupby 值并获取最大日期和最小日期的值

python plotly smith 图表函数行为与 scikit-rf 不同

c++ - 使用 vector 和正斜杠进行字符串算术

datetime - Informix 日期时间 : How to subtract 15 Minutes

python - 将 pandas 时区感知的 DateTimeIndex 转换为天真的时间戳,但在特定时区

java - 这个给定日期的日期格式是什么

python - some_dict.items() 是 Python 中的迭代器吗?

python - 在 Python 中,模拟 Perl 的 __END__ 的最佳方法是什么?

c - Objective-C 字符串,字符串格式化程序