首页 文章

在Python中将各种人类可读时间格式解析为时间对象(datetime.time)?

提问于
浏览
0

我有一个可能是时间对象的字符串列表 . 注意:NOT datetime对象或timestamp对象 . 这些时候没有提及纪元或日期 . 例如:

time_strings = ['6:00PM', '7:00pm', '8:00am', '17:00:00', '4PM']

是否有一个很好的解析实用程序可以将这些转换为datetime.time对象而不是datetime.datetime对象(默认情况下输入当前日期)?

标准的'datetime.datetime.strptime()都要求时间为已知格式并生成datetime.datetime.object,例如:

from datetime import datetime
datetime.strptime('6:00', '%H:%M')

yield:datetime.datetime(1900,1,1,6,0)

我尝试过以下方法:

from dateutil.parser import parse
parse(time_strings[0])

yield:datetime.datetime(2017,8,24,18,0)

import pandas as pd
pd.to_datetime(time_strings[0])

收益率:时间戳('2017-08-24 18: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对象?

1 回答

  • 0

    我发现的最佳解决方案来自pandas核心库:

    from pandas.core.tools.datetimes import to_time
    to_time(time_strings[0])
    

    yield:datetime.time(18,0)

    哪个是所需的输出 . 但是,它不承认时间格式,如(下午4点,3点等)欢迎更好的解决方案 .

相关问题