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

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

我不想要约会时间。对象,而不是Datetime .date对象。


当前回答

对于单个值,为datetime。Strptime法是最快的

import arrow
from datetime import datetime
import pandas as pd

l = ['24052010']

%timeit _ = list(map(lambda x: datetime.strptime(x, '%d%m%Y').date(), l))
6.86 µs ± 56.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit _ = list(map(lambda x: x.date(), pd.to_datetime(l, format='%d%m%Y')))
305 µs ± 6.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit _ = list(map(lambda x: arrow.get(x, 'DMYYYY').date(), l))
46 µs ± 978 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

对于一个值的列表,熊猫pd。To_datetime是最快的

l = ['24052010'] * 1000

%timeit _ = list(map(lambda x: datetime.strptime(x, '%d%m%Y').date(), l))
6.32 ms ± 89.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit _ = list(map(lambda x: x.date(), pd.to_datetime(l, format='%d%m%Y')))
1.76 ms ± 27.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit _ = list(map(lambda x: arrow.get(x, 'DMYYYY').date(), l))
44.5 ms ± 522 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

对于ISO8601 datetime格式,ciso8601是一个火箭

import ciso8601

l = ['2010-05-24'] * 1000

%timeit _ = list(map(lambda x: ciso8601.parse_datetime(x).date(), l))
241 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

其他回答

使用时间模块转换数据。

代码片段:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var
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))

你有一个日期字符串"24052010"你想要一个日期对象,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

这个cus_date将为您提供日期对象。

你可以使用这个从日期对象中检索日期字符串,

cus_date.strftime("%d%m%Y")

如果您很懒,不想与字符串字面值作斗争,您可以直接使用解析器模块。

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

只是一个边注,当我们试图匹配任何字符串表示时,它比strptime慢10倍