Python > format dates > 30 Apr 2020 to epoch time

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


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
 
Back
Top