当我得到这种日期格式时,是否可以将字符串转换为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.