如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
当前回答
创建一个小的实用程序函数,如:
def date(datestr="", format="%Y-%m-%d"):
from datetime import datetime
if not datestr:
return datetime.today().date()
return datetime.strptime(datestr, format).date()
这是足够多功能的:
如果不传递任何参数,它将返回今天的日期。有一个日期格式作为默认值,您可以覆盖它。您可以轻松地修改它以返回日期时间。
其他回答
看看我的答案。
在真实数据中,这是一个真正的问题:多个、不匹配、不完整、不一致和多语言/地区日期格式,通常在一个数据集中自由混合。生产代码失败是不好的,更不用说像狐狸一样高兴异常了。
我们需要尝试。。。捕获多个日期时间格式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
以下是使用Pandas将格式化为字符串的日期转换为datetime.date对象的两种解决方案。
import pandas as pd
dates = ['2015-12-25', '2015-12-26']
# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
计时
dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()
>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop
>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop
下面是如何转换OP的原始日期时间示例:
datetimes = ['Jun 1 2005 1:33PM', 'Aug 28 1999 12:00AM']
>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33),
datetime.datetime(1999, 8, 28, 0, 0)]
使用to_datetime将字符串转换为Pandas时间戳有很多选项,因此如果需要任何特殊信息,请查看文档。
同样,除了.date之外,时间戳还有许多可以访问的财产和方法
使用熊猫时间戳似乎是最快的:
import pandas as pd
N = 1000
l = ['Jun 1 2005 1:33PM'] * N
list(pd.to_datetime(l, format=format))
%timeit _ = list(pd.to_datetime(l, format=format))
1.58 ms ± 21.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
其他解决方案
from datetime import datetime
%timeit _ = list(map(lambda x: datetime.strptime(x, format), l))
9.41 ms ± 95.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
from dateutil.parser import parse
%timeit _ = list(map(lambda x: parse(x), l))
73.8 ms ± 1.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
如果字符串是ISO 8601字符串,请使用csio8601:
import ciso8601
l = ['2014-01-09'] * N
%timeit _ = list(map(lambda x: ciso8601.parse_datetime(x), l))
186 µs ± 4.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
#Convert String to datetime
>>> x=datetime.strptime('Jun 1 2005', '%b %d %Y').date()
>>> print(x,type(x))
2005-06-01 00:00:00 <class 'datetime.datetime'>
#Convert datetime to String (Reverse above process)
>>> y=x.strftime('%b %d %Y')
>>> print(y,type(y))
Jun 01 2005 <class 'str'>
许多时间戳都有一个隐含的时区。为了确保您的代码在每个时区都有效,您应该在内部使用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分钟”源自芝加哥的经度。我使用这个时间戳是因为它正好在芝加哥采用标准时间之前。