Right now I have:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
This works great unless I'm converting a string that doesn't have the microseconds. How can I specify that the microseconds are optional (and should be considered 0 if they aren't in the string)?
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 time strptime() MethodThe 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.
Return Value On successful completion, the strptime() function returns a pointer to the character following the last character parsed. Otherwise, a null pointer is returned.
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..
The strptime() method creates a datetime object from a given string. Note: You cannot create datetime object from every string. The string needs to be in a certain format.
A literal '%' character. If the string (first argument) and the format code (second argument) passed to the strptime () doesn't match, you will get ValueError. For example: If you run this program, you will get an error.
To build a format string without splitting the time string and discarding extra text, just include the extra text in the format string. t [t.index (',',t.index (',') + 1):] is extra text.
You could use a try/except
block:
try: timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f') except ValueError: timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
What about just appending it if it doesn't exist?
if '.' not in date_string: date_string = date_string + '.0' timestamp = datetime.strptime(date_string, '%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