将各种格式的字符串时间转统一格式时间
- 使用了pandas的to_datetime
- yearfirst=True,如果输入的日期为两位数(12/08/09)就默认前面是年份
import pandas as pd
def to_datetime_str(time_str):
"""
各种格式的时间字符串,转时间
:param time_str:
:return:{"succ": True(是否转换成功), "datetime":datetime.datetime格式的时间, "datetime_string": 字符串格式的时间}
"""
new_time = pd.to_datetime(time_str,yearfirst=True, errors='ignore')
if new_time == time_str:
# 特殊格式的时间,可以再这里添加规则
format_list = ["%Y~%m~%d","%Y|%m|%d","%Y~%m~%d %H:%M:%S","%Y|%m|%d %H:%M:%S"]
format_index = 0
while new_time == time_str:
if format_index == len(format_list):
return {"succ": False, "datetime": None, "datetime_string": "没有匹配当前时间的规则"}
new_time = pd.to_datetime(time_str, format=format_list[format_index], yearfirst=True,errors='ignore')
if new_time != time_str:
return {"succ": True, "datetime": new_time.to_pydatetime(), "datetime_string": str(new_time)}
format_index += 1
else:
return {"succ": True, "datetime": new_time.to_pydatetime(), "datetime_string": str(new_time)}
print(to_datetime_str('2007|12|02'))
print(to_datetime_str('07-12-02 23:12:35'))
print(to_datetime_str('20071202231235'))
print(to_datetime_str('2007/12/02 231235'))
print(to_datetime_str('20071202T231235'))
print(to_datetime_str('1202T231235'))
print(to_datetime_str('12/02/2007 231235'))
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 0, 0), 'datetime_string': '2007-12-02 00:00:00'}
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 23, 12, 35), 'datetime_string': '2007-12-02 23:12:35'}
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 23, 12, 35), 'datetime_string': '2007-12-02 23:12:35'}
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 23, 12, 35), 'datetime_string': '2007-12-02 23:12:35'}
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 23, 12, 35), 'datetime_string': '2007-12-02 23:12:35'}
{'succ': False, 'datetime': None, 'datetime_string': '没有匹配当前时间的规则'}
{'succ': True, 'datetime': datetime.datetime(2007, 12, 2, 23, 12, 35), 'datetime_string': '2007-12-02 23:12:35'}