0

I have a sensor that sends a data along with timestamp as a string which is parsed by a python script. The timestamp is then stored in it's own variable that is already formatted in hh:mm:ss like this for example: 23:52:50

What I want to do is create a full datetime object from the incoming timestamp values but so far I've been unable to figure out how.

From what I've seen so far is it a case of splitting the timestamp and storing the incoming timestamps in 3 different variables for hours, minutes and seconds then creating a time object like this: t = time(23, 52, 50)

Afterwards then use datetime.combine to add the date?

Is there a way to achieve this without having to reformat the incoming timestamps and keeping them as they are and just adding on today's date?

techPirate99
  • 146
  • 1
  • 9

1 Answers1

1

Was able to use the method here to do it: Easiest way to combine date and time strings to single datetime object using Python

import datetime as dt

ts = "23:52:52"
mytime = dt.datetime.strptime(ts, "%H:%M:%S").time()
print(mytime)
mydatetime = dt.datetime.combine(dt.date.today(), mytime)
print(mydatetime)
  • be careful with `dt.date.today()` - sometimes, internal clocks of sensors are set to UTC which might be a different timezone than you are in. – FObersteiner Apr 27 '20 at 05:58