如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
当前回答
如果您不想明确指定字符串相对于日期时间格式的格式,可以使用此黑客绕过该步骤:
from dateutil.parser import parse
# Function that'll guess the format and convert it into the python datetime format
def update_event(start_datetime=None, end_datetime=None, description=None):
if start_datetime is not None:
new_start_time = parse(start_datetime)
return new_start_time
# Sample input dates in different formats
d = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']
new = [update_event(i) for i in d]
for date in new:
print(date)
# Sample output dates in Python datetime object
# 2014-04-23 00:00:00
# 2013-04-24 00:00:00
# 2014-04-25 00:00:00
如果要将其转换为其他日期时间格式,只需使用您喜欢的格式修改最后一行,例如date.strftime(“%Y/%m/%d%H:%m:%S.%f”):
from dateutil.parser import parse
def update_event(start_datetime=None, end_datetime=None, description=None):
if start_datetime is not None:
new_start_time = parse(start_datetime)
return new_start_time
# Sample input dates in different formats
d = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']
# Passing the dates one by one through the function
new = [update_event(i) for i in d]
for date in new:
print(date.strftime('%Y/%m/%d %H:%M:%S.%f'))
# Sample output dates in required Python datetime object
# 2021/06/07 06:40:23.277000
# 2021/06/07 06:40:00.000000
# 2021/06/07 00:00:00.000000
尝试运行上面的代码段以获得更好的清晰度。
其他回答
看看我的答案。
在真实数据中,这是一个真正的问题:多个、不匹配、不完整、不一致和多语言/地区日期格式,通常在一个数据集中自由混合。生产代码失败是不好的,更不用说像狐狸一样高兴异常了。
我们需要尝试。。。捕获多个日期时间格式fmt1,fmt2,。。。,fmtn和抑制/处理所有不匹配的异常(来自strptime())(特别是,避免需要try…catch子句的yukky-n-deep缩进阶梯)。从我的解决方案
def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
for fmt in fmts:
try:
return datetime.strptime(s, fmt)
except:
continue
return None # or reraise the ValueError if no format matched, if you prefer
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=“字符串格式时间”
与Javed的回答类似,我只是想要字符串中的日期-所以结合Simon和Javed逻辑,我们得到:
from dateutil import parser
import datetime
s = '2021-03-04'
parser.parse(s).date()
输出
日期时间日期(2021 3月4日)
许多时间戳都有一个隐含的时区。为了确保您的代码在每个时区都有效,您应该在内部使用UTC,并在每次外来对象进入系统时附加一个时区。
Python 3.2+:
>>> datetime.datetime.strptime(
... "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))
这假设您知道偏移量。如果您不知道,但您知道例如位置,您可以使用pytz包查询IANA时区数据库中的偏移量。我将在这里以德黑兰为例,因为它有半小时的偏移量:
>>> tehran = pytz.timezone("Asia/Tehran")
>>> local_time = tehran.localize(
... datetime.datetime.strptime("March 5, 2014, 20:13:50",
... "%B %d, %Y, %H:%M:%S")
... )
>>> local_time
datetime.datetime(2014, 3, 5, 20, 13, 50, tzinfo=<DstTzInfo 'Asia/Tehran' +0330+3:30:00 STD>)
如您所见,pytz已确定在特定日期的偏移量为+3:30。您现在可以将其转换为UTC时间,它将应用偏移量:
>>> utc_time = local_time.astimezone(pytz.utc)
>>> utc_time
datetime.datetime(2014, 3, 5, 16, 43, 50, tzinfo=<UTC>)
请注意,采用时区之前的日期会给您带来奇怪的偏移。这是因为IANA决定使用本地平均时间:
>>> chicago = pytz.timezone("America/Chicago")
>>> weird_time = chicago.localize(
... datetime.datetime.strptime("November 18, 1883, 11:00:00",
... "%B %d, %Y, %H:%M:%S")
... )
>>> weird_time.astimezone(pytz.utc)
datetime.datetime(1883, 11, 18, 7, 34, tzinfo=<UTC>)
奇怪的“7小时34分钟”源自芝加哥的经度。我使用这个时间戳是因为它正好在芝加哥采用标准时间之前。
arrow为日期和时间提供了许多有用的函数。这段代码为这个问题提供了答案,并表明箭头还能够轻松格式化日期并显示其他地区的信息。
>>> import arrow
>>> dateStrings = [ 'Jun 1 2005 1:33PM', 'Aug 28 1999 12:00AM' ]
>>> for dateString in dateStrings:
... dateString
... arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').datetime
... arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')
... arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')
...
'Jun 1 2005 1:33PM'
datetime.datetime(2005, 6, 1, 13, 33, tzinfo=tzutc())
'Wed, 1st Jun 2005 13:33'
'vor 11 Jahren'
'Aug 28 1999 12:00AM'
datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())
'Sat, 28th Aug 1999 00:00'
'vor 17 Jahren'
看见http://arrow.readthedocs.io/en/latest/了解更多信息。