datetime从Python中的字符串,最好的猜测字符串格式 [英] datetime from string in Python, best-guessing string format

查看:196
本文介绍了datetime从Python中的字符串,最好的猜测字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字符串 datetime.strptime(date_string,format)获取日期时间的函数需要一个字符串格式作为第二个参数。有没有办法从字符串构建datetime而不知道确切的格式,并且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作为处理时区的不可或缺lib

(请参阅将UTC datetime字符串转换为本地日期时间如何将本地时间转换为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 datetime字符串转换为Python datetime对象?

这篇关于datetime从Python中的字符串,最好的猜测字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆