How to Add Milliseconds to Datetime in Python
Precise time manipulation is essential in many programming tasks.
This guide focuses on adding milliseconds to datetime
and time
objects in Python, using the timedelta
class. We'll explore how to work with existing datetime
objects, current time, formatting, and handling cases involving only time components.
Adding Milliseconds to a datetime
Object
You can add milliseconds to a datetime
object created from a string using the timedelta()
class:
from datetime import datetime, timedelta
date_string = '2024-11-24 09:30:00.000123'
datetime_object = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
result = datetime_object + timedelta(milliseconds=300)
print(result) # Output: 2024-11-24 09:30:00.300123
datetime.strptime()
parses the date and time string.- The
timedelta(milliseconds=300)
creates atimedelta
object representing a duration of 300 milliseconds. - The result shows that 300 milliseconds have been added to the datetime object
datetime_object
.
Creating datetime
Objects and Adding Milliseconds
You can also add milliseconds to a datetime
object constructed directly:
from datetime import datetime, timedelta
dt = datetime(2024, 9, 24, 9, 30, 35)
result = dt + timedelta(milliseconds=400)
print(result) # Output: 2024-09-24 09:30:35.400000
Adding Milliseconds to the Current Time
To add milliseconds to the current time, use datetime.today()
to get a datetime object:
from datetime import datetime, timedelta
current_time = datetime.today()
result = current_time + timedelta(milliseconds=500)
print(result) # Output (Will depend on the current date and time, but with milliseconds added)
datetime.today()
gets the current date and time.timedelta
is used to add the milliseconds, and updates the seconds, minutes, etc. as needed.
Adding Milliseconds to a time
Object
If you have just a time
object, you can't directly add timedelta
as time
objects store only the time component. Use datetime.combine()
to get a datetime object:
from datetime import datetime, date, timedelta, time
t = time(6, 25, 30, 123) # time object
result = datetime.combine(date.today(), t) + timedelta(milliseconds=400)
print(result) # Output (Will vary depending on current date)
only_time = result.time()
print(only_time) # Output: 06:25:30.400123
datetime.combine()
creates adatetime
object from today's date combined witht
.timedelta
is added to the combineddatetime
object.result.time()
extracts thetime
part after adding the milliseconds.
Extracting Time Components
Use the .time()
method to get the time component of a datetime
object:
from datetime import datetime, date, timedelta, time
t = time(6, 25, 30, 123)
result = datetime.combine(date.today(), t) + timedelta(milliseconds=400)
only_t = result.time()
print(only_t) # Output: 06:25:30.400123