日期时间来自 Python 中的字符串,最佳猜测字符串格式 [英] datetime from string in Python, best-guessing string format
问题描述
从字符串中获取日期时间的函数,datetime.strptime(date_string, format)
需要一个字符串格式作为第二个参数.有没有办法在不知道确切格式的情况下从字符串构建日期时间,并且让 Python 猜测它?
The function to get a datetime from a string, datetime.strptime(date_string, format)
requires a string format as the second argument. Is there a way to build a datetime from a string without without knowing the exact format, and having Python best-guess it?
推荐答案
使用 dateutil 图书馆.
我已经在使用 dateutil 作为处理时区的不可或缺的库
(参见将UTC日期时间字符串转换为本地日期时间和如何在 Python 中将当地时间转换为 UTC?)
I was already using dateutil as an indispensable lib for handling timezones
(See Convert UTC datetime string to local datetime and How do I convert local time to UTC in Python?)
我刚刚意识到它具有日期解析支持:
And I've just realized it has date parsing support:
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
(另请参阅如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象?)
这篇关于日期时间来自 Python 中的字符串,最佳猜测字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!