How to convert HH:MM:SS to time.time() object in Python

Viewed 3838

I need to convert HH:MM:SS format to time.time() object. Is there any way to do it?

Here's my HH:MM:SS format time:

a = '14:37:29'

I want to convert it to time.time() object such as:

a = 1600256249

Is this achievable? If it's not, what should I try? Hope you help.

2 Answers

To get UNIX time, you need to add a date. For example, you could combine your time string with today's date:

from datetime import datetime, timezone

s = '14:37:29'
today = datetime.today() # 2020-09-16

# make a datetime object with today's date
dt = datetime.combine(today, datetime.strptime(s, '%H:%M:%S').time())

# make sure it's in UTC (optional)
dt = dt.replace(tzinfo=timezone.utc)

# get the timestamp
ts = dt.timestamp()
print(ts)
# 1600267049.0

You could also set other time zones with this approach using dateutil or zoneinfo (Python 3.9+).

Is this achievable?

I would say no. a = '14:37:29' holds only hour-minute-second, whilst time.time() does return seconds since start of epoch i.e. you would also need to known day, month and year beside hour, minute, second, to create equivalent of what time.time() returns.

Related