Python: How can I convert string to datetime without knowing the format?

亡梦爱人 提交于 2020-07-08 04:05:06

问题


I have a field that comes in as a string and represents a time. Sometimes its in 12 hour, sometimes in 24 hour. Possible values:

  1. 8:26
  2. 08:26am
  3. 13:27

Is there a function that will convert these to time format by being smart about it? Option 1 doesn't have am because its in 24 hour format, while option 2 has a 0 before it and option 3 is obviously in 24 hour format. Is there a function in Python/ a lib that does:

time = func(str_time)

回答1:


super short answer:

from dateutil import parser
parser.parse("8:36pm")
>>>datetime.datetime(2015, 6, 26, 20, 36)
parser.parse("18:36")
>>>datetime.datetime(2015, 6, 26, 18, 36)

Dateutil should be available for your python installation; no need for something large like pandas

If you want to extract the time from the datetime object:

t = parser.parse("18:36").time()

which will give you a time object (if that's of more help to you). Or you can extract individual fields:

dt = parser.parse("18:36")
hours = dt.hour
minute = dt.minute



回答2:


there is one such function in pandas

import pandas as pd
d = pd.to_datetime('<date_string>')


来源:https://stackoverflow.com/questions/31066805/python-how-can-i-convert-string-to-datetime-without-knowing-the-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!