Recent Posts

Convert string to datetime with Python

Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised. The default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1).

>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")   
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
Check out strptime in the time module. It is the inverse of strftime.

Otherwise you can use the third party dateutil library:

from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")
It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.


No comments:

Post a Comment