Python日期字符串到日期对象

2024-04-19 01:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中将字符串转换为日期对象?

字符串应该是:"24052010"(对应于格式:"%d%m%Y"

我不需要datetime.datetime对象,而是需要datetime.date。


Tags: 对象字符串datetimedate格式中将
3条回答
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

直接相关问题:

如果你有

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

你会得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

你试过:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

但你还是能找到上面的线索。

回答:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

您可以在Python的^{}包中使用^{}

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

相关问题 更多 >