Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing non-zero padded timestamps in Python

I want to get datetimes from timestamps like the following :3/1/2014 9:55 with datetime.strptime, or something equivalent.

The month, day of month, and hour is not zero padded, but there doesn't seem to be a formatting directive listed here that is able to parse this automatically.

What's the best approach to do so? Thanks!

like image 237
Pythontology Avatar asked Aug 13 '14 07:08

Pythontology


People also ask

What is Strptime and Strftime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

What is the use of Strptime in Python?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.

What is parsing dates in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options. Not too bad … and powerful.


2 Answers

strptime is able to parse non-padded values. The fact that they are noted as being padded in the formatting codes table applies to strftime's output. So you can just use

datetime.strptime(datestr, "%m/%d/%Y %H:%M") 
like image 73
Jason S Avatar answered Sep 20 '22 17:09

Jason S


strptime isdo not require 0-padded values. See example below

datetime.strptime("3/1/2014 9:55", "%m/%d/%Y %H:%M") output:   datetime.datetime(2014, 3, 1, 9, 55) 
like image 33
gaw Avatar answered Sep 20 '22 17:09

gaw