datetime从Python中的字符串,最好的猜测字符串格式

编程入门 行业动态 更新时间:2024-10-27 13:30:39
本文介绍了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中的字符串,最好的猜测字符串格式

本文发布于:2023-11-22 15:23:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   最好的   格式   datetime   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!