2

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.

Mustafa
  • 59
  • 1
  • 9
  • 2
    Is a a string? If so you you can start looking over here: https://stackoverflow.com/questions/466345/converting-string-into-datetime – Uberhumus Sep 16 '20 at 11:43
  • 1
    Please make sure you read all answers in the suggested duplicate. Your question might not be answered in the accepted answer – Exelian Sep 16 '20 at 11:47

2 Answers2

2

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+).

C.Kelly
  • 215
  • 1
  • 12
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
1

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.

Daweo
  • 31,313
  • 3
  • 12
  • 25