Python 日期字符串到日期对象
- 2025-01-09 08:46:00
- admin 原创
- 162
问题描述:
如何在 python 中将字符串转换为日期对象?
该字符串将是:("24052010"
对应格式"%d%m%Y"
:)
我不想要 datetime.datetime 对象,而是 datetime.date。
解决方案 1:
strptime
您可以在datetime
Python包中使用:
>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)
解决方案 2:
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()
解决方案 3:
直接相关的问题:
如果你有
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))
解决方案 4:
如果您很懒并且不想与字符串文字作斗争,那么您可以使用模块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
解决方案 5:
你有一个像这样的日期字符串,“24052010”,并且你想要这个日期对象,
from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()
这个 cus_date 将为您提供日期对象。
您可以使用这个从日期对象中检索日期字符串,
cus_date.strftime("%d%m%Y")
解决方案 6:
对于单值,该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)
对于值列表,pandaspd.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 日期时间格式来说这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)
解决方案 7:
还有一个名为arrow
“非常棒”的库可以对 python 日期进行操作。
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
解决方案 8:
字符串“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
解决方案 9:
使用时间模块转换数据。
代码片段:
import time
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD