Python日期字符串到日期对象

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

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

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

607046 次浏览
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

你可以在Python的datetime包中使用strptime:

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

直接相关的问题:

如果你有

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))

使用时间模块转换数据。

代码片段:

import time
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

还有一个名为arrow的库非常适合在python date上进行操作。

import arrow
import datetime


a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True

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

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

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

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

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

如果你很懒,不想与字符串文字作斗争,你可以直接使用parser模块。

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

只是题外话,当我们试图匹配any字符串表示时,它比strptime慢10倍

对于单个值,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)

对于值列表,pandas 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)
< p >字符串“24052010”; 在一个非常手动的方式,你可以这样做:- 首先将字符串分割为(yyyy-mm-dd)格式,这样您就可以得到一个类似于(2010,5,24)的元组,然后简单地将这个元组转换为日期格式,例如2010-05-24

您可以在类似于上面的字符串对象列表上运行此代码,并通过简单地解包(*tuple)检查下面的代码,将整个元组对象列表转换为日期对象。

import datetime
#for single string simply use:-


my_str= "24052010"
date_tup = (int(my_str[4:]),int(my_str[2:4]),int(my_str[:2]))
print(datetime.datetime(*date_tup))


output: 2012-01-01 00:00:00


# for a list of string date objects you could use below code.
date_list = []
str_date = ["24052010", "25082011", "25122011","01012012"]


for items in str_date:
date_list.append((int(items[4:]),int(items[2:4]),int(items[:2])))


for dates in date_list:
# unpack all tuple objects and convert to date
print(datetime.datetime(*dates))


output:
2010-05-24 00:00:00
2011-08-25 00:00:00
2011-12-25 00:00:00
2012-01-01 00:00:00