convert from date string to epoch

John Machin sjmachin at lexicon.net
Mon Dec 18 12:36:04 EST 2006


Stefan Antonelli wrote:
> Amit Khemka <khemkaamit <at> gmail.com> writes:
> >
> > Check out timegm function in calendar module. The following function
> > converts "mm/dd/yyyy" formats into epoch value, you can hack it for
> > your date formats.
> >
> > def convertToEpoch(date):
> >          tup = map(int,date.split('/'))
> >          l = (tup[2], tup[0], tup[1], 0, 0, 0)
> >          epochs = calendar.timegm(l)
> >          return (int(epochs))
>
>
> Thanks for your suggestion... For me this was the Solutions:
>
> # convert 'yyyy-mm-dd hh:mm:ss' to epoch
> def toEpoch(timestamp):
>   split = str(timestamp).split(' ')

Binding the name "split" to this result is not a good idea, because it
leads to ...

>   tdate = map(int,split[0].split('-'))

... the above line being rather difficult to read without exclamations
:-)

>   ttime = map(int,split[1].split(':'))
>   tcode = (tdate[0], tdate[1], tdate[2], ttime[0], ttime[1], ttime[2])

... and the above causes the same problem.

    tcode = ttime + tcode

might be better.

>   epoch = timegm(tcode)
>   return (int(epoch))
>

Try this:

 def toEpoch(timestamp):
  datestr, timestr = str(timestamp).split(' ')
  tdate = datestr.split('-')
  ttime = timestr.split(':')
  tcode = map(int, tdate + ttime)
  epoch = timegm(tcode)
  return int(epoch)

Note: the last 5 lines can be jammed into one line if you are desperate
:-)

HTH,
John




More information about the Python-list mailing list