如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
当前回答
与Javed的回答类似,我只是想要字符串中的日期-所以结合Simon和Javed逻辑,我们得到:
from dateutil import parser
import datetime
s = '2021-03-04'
parser.parse(s).date()
输出
日期时间日期(2021 3月4日)
其他回答
使用第三方dateutil库:
from dateutil import parser
parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0)
它可以处理大多数日期格式,并且比strptime更方便,因为它通常猜测正确的格式。它对于编写测试也非常有用,因为可读性比性能更重要。
安装时使用:
pip install python-dateutil
这里没有提到但很有用的一点:在当天添加后缀。我解耦了后缀逻辑,这样你就可以将它用于任何你喜欢的数字,而不仅仅是日期。
import time
def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy
tens = int(str(n)[-2:])
units = n % 10
if tens > 10 and tens < 20:
return suf[0] # teens with 'th'
elif units <= 3:
return suf[units]
else:
return suf[0] # 'th'
def day_suffix(t):
'''
Returns the suffix of the given struct_time day
'''
return num_suffix(t.tm_mday)
# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))
In [34]: import datetime
In [35]: _now = datetime.datetime.now()
In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)
In [37]: print _now
2016-01-19 09:47:00.432000
In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")
In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)
In [40]: assert _now == _parsed
您还可以查看dateparser:
dateparser提供了模块,可以在几乎网页上常见的任何字符串格式。
安装:
pip install dateparser
我认为这是解析日期的最简单方法。
最直接的方法是使用dateparser.parse函数,它包含了模块中的大部分功能。
示例代码:
import dateparser
t1 = 'Jun 1 2005 1:33PM'
t2 = 'Aug 28 1999 12:00AM'
dt1 = dateparser.parse(t1)
dt2 = dateparser.parse(t2)
print(dt1)
print(dt2)
输出:
2005-06-01 13:33:00
1999-08-28 00:00:00
datetime.strptime将用户指定格式的输入字符串解析为时区原始日期时间对象:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
要使用现有的datetime对象获取日期对象,请使用.date()对其进行转换:
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
链接:
strptime文档:Python 2、Python 3strptime/strftime格式字符串文档:Python 2,Python 3strftime.org格式字符串备忘单
笔记:
strptime=“字符串解析时间”strftime=“字符串格式时间”