如何解析包含“ st”,“ nd”,“ rd”或“ th”的日期日期? [英] How to parse date days that contain "st", "nd", "rd", or "th"?

查看:423
本文介绍了如何解析包含“ st”,“ nd”,“ rd”或“ th”的日期日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串

"1st January 2014"

我想将其解析为 datetime.date 。我可以这样做:

I want to parse it into a datetime.date. I can do this:

如果日期是 2014年1月1日
,我会这样做: replace('','')然后 datetime.strptime(SecondDateString,%d%B%Y)。date()

但是当一天有 st nd rd th

编辑:
您可能会说我自己删除了 st nd rd th ,然后在上面使用我自己的方式,是的,这是一个解决方案,但我

you may say that I myself remove the st, nd, rd, or th and then use my own way above, yes this is a solution but I am asking if python has already had something for me.

推荐答案

您可以使用 regex 替换 st nd rd th 带有空字符串:

You can use regex to replace st, nd, rd, th with an empty string:

import re
def solve(s):                                             
    return re.sub(r'(\d)(st|nd|rd|th)', r'\1', s)

演示:

>>> datetime.strptime(solve('1st January 2014'), "%d %B %Y")
datetime.datetime(2014, 1, 1, 0, 0)
>>> datetime.strptime(solve('3rd March 2014'), "%d %B %Y")
datetime.datetime(2014, 3, 3, 0, 0)
>>> datetime.strptime(solve('2nd June 2014'), "%d %B %Y")
datetime.datetime(2014, 6, 2, 0, 0)
>>> datetime.strptime(solve('1st August 2014'), "%d %B %Y")
datetime.datetime(2014, 8, 1, 0, 0)

这篇关于如何解析包含“ st”,“ nd”,“ rd”或“ th”的日期日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆