简体   繁体   中英

How to convert datetime.strptime() weird date format ( with the word “of” in it)?

当我得到这种日期格式时,是否可以将字符串转换为datetime对象:

9th of April 2015 03:00

You can also let dateutil do the job:

>>> from dateutil.parser import parse
>>> s = "9th of April 2015 03:00"
>>> parse(s)
datetime.datetime(2015, 4, 9, 3, 0)

Alternatively:

t = '9th of April 2015 03:00'
prefix = t.split()[0][-2:]
datetime.datetime.strptime(t, '%d{0} of %B %Y %H:%M'.format(prefix))

datetime.datetime(2015, 4, 9, 3, 0)

Updated: However I believe @alecxe's answer is the best among for general use case.

Yes, you just need to specify a correct position and type for your datetime objects!

>>> datetime.datetime.strptime('9th of April 2015 03:00','%dth of %B %Y %H:%M')
datetime.datetime(2015, 4, 9, 3, 0)

Note that as mentioned in comment you can't use of this recipe for other strings that contain other numbers of day like 1st and 2nd , so as a more general way as @alecxe mentioned you can use dateutil.parser.parse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM