'How to convert time object to datetime object in python? [duplicate]

I have timestamp which is a time object and trying to convert it to a datetime object because datetime has stonger capabilities and I need to use some function that only datetime has.
The reason I'm starting with time is because datetime doesn't support milliseconds which the original string contains.

What is the easiest way to do it?



Solution 1:[1]

assuming timestamp is an time object and datetimestamp will be the datetime object:

from datetime import datetime
import time

timestamp = time.strptime('2022-03-02 02:45:12.123', '%Y-%m-%d %H:%M:%S.%f')
datetimestamp = datetime(*timestamp[:5])

It works because time is actually a tuple with the following structure (year, month, day, hour, minute, seconds....), and the datetime __init__ expects the same sequence of variables

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1