1

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?

7
  • "because datetime doesn't support milliseconds - what makes you think that? Just because there is no attribute "milliseconds" doesn't mean you cannot work with them - just multiply by 10^3 and use the microseconds attribute ;-) Commented Mar 2, 2022 at 13:33
  • docs.python.org/3/library/time.html#time.strftime time.strftime doesn't support printing milli or microsecond. unlike datetime.strftime docs.python.org/3/library/… . (and the same about strptime..) Commented Mar 2, 2022 at 13:40
  • your question says nothing about strftime. please clarify if this should be helpful for others. Commented Mar 2, 2022 at 13:41
  • btw. there also seems to be confusion about datetime and time objects vs. the modules with the same name. There is e.g. a datetime.time class, where you can use strftime without problems to create a string with milliseconds precision: datetime.time(1,2,3,444000).strftime('%H:%M:%S.%f')[:-3] Commented Mar 2, 2022 at 13:44
  • 1
    I referred it as time object because it's the return value of time.strptime.. BUT, you are right.. I'll flag the question as duplicate. Thanks for the interesting discussion Commented Mar 2, 2022 at 14:05

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

timestamp is a time.struct_time object for clarification. But why not simply datetimestamp = datetime.fromisoformat('2022-03-02 02:45:12.123') ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.