Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Datetime / Unix Date convertor

I need an input prompt that will allow the user to enter a date at the point the function is called and then run to concert the date to Unix date for an API call later in the program.
At the moment every attempt seems to hand back an error regarding Str, to Int.

I get the function wants to convert the date in line 9 to a date time value but I can’t create an input that I could then convert.

def unixconvert() :
# importing datetime module
    import datetime
    import time
    # assigned regular string date
    date_time = datetime.datetime(2021, 7, 26, 21, 20)
    # print regular python date&time
    print("date_time =>",date_time) 
    # displaying unix timestamp after conversion
    print("unix_timestamp => ",
        (time.mktime(date_time.timetuple())))

I have tried a standard input(‘enter a date’)
I have tried passing a multiple variables and trying to build the input, year =, month = etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What about something like this:

def unixconvert():                                                
                                         
    date_time_input = input() #something like 2021-7-26-21-20

    date_time = datetime.datetime(*(int(x) for x in date_time_input.split('-')))

    print("date_time =>",date_time)

    print("unix_timestamp => ", (time.mktime(date_time.timetuple())))

It’s basically split by - and convert every number to int.


Maybe something like this is more clear:

year, month, day, hours, minutes = (int(x) for x in date_time_input.split('-'))
date_time = datetime.datetime(year, month, day, hours, minutes)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading