Python > format dates > 30 Apr 2020 to epoch time

Discussion in 'App Development' started by OptionsOptionsOptions, Apr 30, 2020.

  1. Does Python date function support formatting 30 Apr 2020 to epoch time?

    • I Googled it and don't think so.
    • If not I will write my own function.
    Thanks
     
  2. tiddlywinks

    tiddlywinks

  3. Input has to be 30 Apr 2020

    I don't think Python's date function can handle converting Jan,Feb,Apr,May,etc to the corresponding month: 01,02,03,04,etc

    That's why I think I have to create my own function.
     
  4. I’m certain that it can be done; can take a look later. If not, quickly move your data to R, where I know it can be done.
     
  5. tiddlywinks

    tiddlywinks


    https://mkaz.blog/code/python-dates/

    This is not difficult or obscure.
     

    • Your link is no good - it doesn't have a solution.
    • It looks like Python's datetime function can't do it, as I suspected.
    • So I will be writing my own function.
     
  6. gaussian

    gaussian

  7. Thanks everyone for the replies. I have decided to create my own function. This is what I have:

    • Input: 26 Feb 2020
    • Output: 2020-02-26
    • The final step to epoch time will be added later.

    Python code
    Code:
    def dateFormat(input):
       array = input.split()
    
       months={'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06',
       'Jul':'07','Aug':'08','Sep':'09','Sept':'09','Oct':'10','Nov':'11','Dec':'12'}
    
       day,month,year = array[0],array[1],array[2]
       month = (months[month])
    
       print(year + "-" + month + "-" + day)
    
    dateFormat('26 Feb 2020')
     

  8. Python can do this in one line: (okay 3 if you count the import and the function header)

    Code:
    import datetime
    def dateFormat(date_string):
        return datetime.datetime.strptime(date_string,"%d %b %Y").strftime("%Y-%m-%d")
    This is helpful https://strftime.org


    Epoch time, to be fair, is a bit trickier, but not much:

    Code:
    def epochTime(date_string):
        dt = datetime.datetime.strptime(date_string,"%d %b %Y")
    
        # there are ways of getting this rather than hard coding if you're bothered
        epoch = datetime.datetime(1970, 1, 1, 0, 0)
        return (dt-epoch).total_seconds()
    
    epochTime("26 Feb 2020")
    
    I'm guessing you're relatively new to python. It often seems quicker to write your own stuff rather than spend a few minutes working out if someone already thought of this, but in the long run definitely better to use built in functions.

    GAT
     
  9. 2rosy

    2rosy

    time.mktime(time.strptime(YOURDT, DTFORMAT))
     
    #10     May 1, 2020