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!
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.
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.
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.
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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With