How can I parse a time string containing milliseconds in it with python?
Python 2.6 added a new strftime/strptime macro %f
. The docs are a bit misleading as they only mention microseconds, but %f
actually parses any decimal fraction of seconds with up to 6 digits, meaning it also works for milliseconds or even centiseconds or deciseconds.
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
However, time.struct_time doesn't actually store milliseconds/microseconds. You're better off using datetime
, like this:
>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000
As you can see, .123
is correctly interpreted as 123 000
microseconds.
Converting string to datetime with milliseconds and timezone - Python
EDIT 2: According to this post, strptime
doesn't support %z
(despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)
Gives the following output:
$ python date.py
2015-01-05 17:47:59
EDIT: Your datetime.strptime
argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'
With strptime()
, %y
refers to
Year without century as a zero-padded decimal number
I.e. 01
, 99
, etc.
If you want to use the full 4-digit year, you need to use %Y
Similarly, if you want to use the 3-letter month, you need to use %b
, not %m
I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Format a datetime into a string with milliseconds
To get a date string with milliseconds, use [:-3]
to trim the last three digits of %f
(microseconds):
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
Or slightly shorter:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
Convert milliseconds to string %H%M%S.%f
create your timedelta object
from datetime import timedelta
ms = 23500
time = timedelta(milliseconds=ms)
now print the result
print(time) # output: 0:00:02.35
or save the result in a variable
result = time.__str__()
From string to datetime with or without millisecond
l = ['03:18:45.2345', '03:19:23']
for item in l:
time_format = "%H:%M:%S.%f" if '.' in item else "%H:%M:%S"
print datetime.datetime.strptime(item, time_format)
Related Topics
How to Exchange Keys with Values in a Dictionary
Running an Outside Program (Executable) in Python
Matplotlib: Annotating a 3D Scatter Plot
How to Pass Optional Parameters to a Function
Applying Udfs on Groupeddata in Pyspark (With Functioning Python Example)
Possible to Share In-Memory Data Between 2 Separate Processes
Pythonic Way of Checking If a Condition Holds for Any Element of a List
Import Pandas Dataframe Column as String Not Int
How to Change the Default MySQL Connection Timeout When Connecting Through Python
Multiprocessing Example Giving Attributeerror
Quick Way to Upsample Numpy Array by Nearest Neighbor Tiling
In Python Interpreter, Return Without " ' "
How to Sort Python List of Strings of Numbers