converting epoch time to string (and vice versa)

Paul Boddie paul at boddie.org.uk
Tue Mar 13 07:57:26 EDT 2007


On 13 Mar, 06:52, "Amit Khemka" <khemkaa... at gmail.com> wrote:
> On 3/13/07, Astan Chee <s... at al.com.au> wrote:
>
> > I have a string in this format "DD/MM/YYY" for example:
> > tdate = "18/01/1990"
> > and Im trying to convert this to epoch time, can anyone help?
>
> import calendar
> t = map(int,tdate.split('/'))
> epochs = calendar.timegm((t[2], t[1], t[0], 0, 0, 0))

You can also use strptime:

import time
t = time.strptime("18/01/1990", "%d/%m/%Y")
epochs = calendar.timegm(t)

Whilst timegm is a hidden gem in the calendar module, it is actually
based on a library function on certain platforms. I've submitted a
patch to add a platform-independent version to the time module -
requests to add such a function previously led only to documentation
changes, I believe. (I think that many people regard mktime as doing
the work that only timegm actually accomplishes, so it's an important
addition.)

> > Im also trying to convert that epoch time to the string format
> > previously. Can anyone help this one too?
>
> import time
> time.ctime(epochs)

Note that ctime makes a string in a particular format (not the
original one, though) from the local time. It might be better to use
strftime instead:

import time
time.strftime("%d/%m/%Y", epochs)

Paul




More information about the Python-list mailing list