I want to extract the timestamp from a string, but the milliseconds part is not being read properly
datetime.strptime('20130629110924095','%Y%m%d%H%M%S%f')
produces the following output
datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)
instead of
datetime.datetime(2013, 6, 29, 11, 9, 24, 95)
to be clear: 95 milliseconds
What am I doing wrong?
strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime object.
Description. Python time method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
Use the timedelta() class from the datetime module to add milliseconds to datetime, e.g. result = dt + timedelta(milliseconds=300) . The timedelta class can be passed a milliseconds argument and adds the specified number of milliseconds to the datetime.
Python time strptime() function 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.
How strptime () works? This function takes two arguments, a string in which some time is given and a format code, to change the string into, the string is changed to the DateTime object as per the list of codes given below. 1, 2..
If you specify the abbreviates in the wrong order or use the wrong format, then the Python strptime function throws an error. from datetime import datetime as rdm dt_string = '31/12/18' dval = rdm.strptime (dt_string, '%d %m %y') print (dval)
The missing piece was an extra space after the string which was causing a format mismatch. So the solution was to call strip () on the string before passing it to strptime (). Read the format strip syntax of strptime (). datetime objects are very handy and general operations such as comparison are inbuilt.
To use this function to produce milliseconds in python %f is used in format code. Given below are some implementations. # object with milliseconds.. Writing code in comment?
The documentation says:
%f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.
So the result you get is expected behaviour, your '095' is padded to '095000'.
Microseconds consist of six digits. 95 milliseconds = 95000 microseconds.
So to get datetime with 95 milliseconds like datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)
write:
datetime.strptime('20130629110924095000','%Y%m%d%H%M%S%f')
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