我有一个字符串列表,这些字符串可能是时间对象。注意:不是日期时间对象或时间戳对象。这些时代没有提到时代或日期。例如:
time_strings = ['6:00PM', '7:00pm', '8:00am', '17:00:00', '4PM']是否有一个好的解析实用程序可以将这些转换为datetime.time对象,而不是datetime.datetime对象(默认情况下,datetime.datetime对象输入当前日期)?
标准的'datetime.datetime.strptime()既要求时间为已知格式,又生成一个datetime.datetime.object,例如:
from datetime import datetime
datetime.strptime('6:00', '%H:%M')收益率: datetime.datetime(1900,1,1,6,0)
我尝试了以下几点:
from dateutil.parser import parse
parse(time_strings[0])收益率: datetime.datetime(2017,8,24,18,0)
import pandas as pd
pd.to_datetime(time_strings[0])收益率:时间戳(‘2017-08-24:00:00“)
from pytimeparse import parse as tparse
tparse(time_strings[0])失败(返回空值)
import parsedatetime
cal = parsedatetime.Calendar()
cal.parse(time_strings[0])产量:(time.struct_time(tm_year=2017,tm_mon=8,tm_mday=24,tm_hour=18,tm_min=0,tm_sec=0,tm_wday=3,tm_yday=236,tm_isdst=1),2)
就我的目的而言,如果没有在数据中推断日期,这是至关重要的。
是否有更好的python实用程序(python 3)将各种人类可读的时间表达式转换为datetime.time对象?
发布于 2017-08-24 21:28:07
我找到的最佳解决方案是从熊猫核心图书馆找到的:
from pandas.core.tools.datetimes import to_time
to_time(time_strings[0])收益率: datetime.time(18,0)
这是所需的输出。然而,它不识别时间格式,如(下午4点,凌晨3点等)。欢迎更好的解决方案。
https://stackoverflow.com/questions/45871166
复制相似问题