S. ARAVIND
S. ARAVIND

Reputation: 19

Convert human readable time to epoch timestamp in Python

I am training to convert human readable time to epoch time. This is my test case

import time
text = '12.12.2020'
format = ['%d/%m/%Y','%m/%d/%Y','%d-%m-%Y','%m-%d-%Y','%d.%m.%Y','%m.%d.%Y','%d%m%Y','%m%d%Y']
for fmt in format:
        try:
            epoch = int(time.mktime(time.strptime(text,fmt)))
            print (epoch)
            break
        except ValueError:
            print('invalid input')

This above code prints 4 time "invalid input" then 5th line prints correct epoch value, Because my text='12.12.2020' input string meets 5th condition. I need to print if my "text" condition meets any of those format then print only epoch value, otherwise print "invalid input". Could anyone help me to solve this ? Thanks in advance.

Upvotes: 0

Views: 1265

Answers (1)

J. M. Arnold
J. M. Arnold

Reputation: 6849

First things first, I'd highly suggest not using the keyword format as a variable name due to it being a built-in function from Python itself (https://docs.python.org/3/library/functions.html). This is called bad practice when assigning variable names.


Anyway, regarding your problem: Your approach isn't so far off - you were missing a slight change:
import time

format_list = ['%d/%m/%Y','%m/%d/%Y','%d-%m-%Y','%m-%d-%Y','%d.%m.%Y','%m.%d.%Y','%d%m%Y','%m%d%Y']
text = '12.1s2.2020'

for fmt in format_list:
    try:
        epoch = int(time.mktime(time.strptime(text,fmt)))
        break
    except:
        epoch = 'invalid input'
        pass

This iterates through your format_list and tries assigning the converted time to the variable epoch. Instead of printing 'invalid error', as you did, I just assign it to epoch, hence if the for-loop went through all eight possibilities without succeeding, epoch equals 'invalid input'. However, if the statement epoch = int(time.mktime(time.strptime(text,fmt))) is true the for-loop breaks, hence the last assignment, being the proper value you wanted, lasts.

You may output epoch via the print() function:

print(epoch)

The output in this case is: 1607727600.

Upvotes: 1

Related Questions