开发者

Parse a string with a date to a datetime object [duplicate]

开发者 https://www.devze.com 2022-12-10 22:27 出处:网络
This question already has answers here: Convert string "Jun 1 2005 1:33PM" into datetime 开发者_如何学JAVA(26 answers)
This question already has answers here: Convert string "Jun 1 2005 1:33PM" into datetime 开发者_如何学JAVA(26 answers) Closed 9 years ago.

How can I parse a string like "01-Jan-1995" to a Python datetime object?


On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:

import datetime
datetime.datetime.strptime("01-Jan-1995", "%d-%b-%Y")

Note that parsing month names is locale-dependent. This table shows the directives for parsing various formats of dates and times.


dateutil can parse this sort of format without you even having to define custom date formats. Just install it with:

pip install python-dateutil

Then use it:

import dateutil.parser
dateutil.parser.parse('01-Jan-1995').date()


If you need to parse natural language date and time strings, consider parsedatetime (and this answer).

0

精彩评论

暂无评论...
验证码 换一张
取 消