from date/time string to seconds since epoch

P

Peter Kleiweg

Is there a safe and clean way to parse a date/time string into
seconds since epoch?

I have a string with date and time in GMT. I can get the correct
value using this:


#!/usr/bin/env python
import os
os.environ['TZ'] = 'UTC'
import time
s = 'Wed, 06 Jul 2005 16:49:38 GMT'
seconds = time.mktime(time.strptime(s, '%a, %d %b %Y %H:%M:%S %Z'))


However, I also need conversions to localtime. Setting TZ to UTC
before importing the time module won't let me do this. Changing
TZ after importing time has no effect.
 
W

wittempj

You can calculate the offset of where you are like this:

martin@ubuntu:~ $ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> import time
py> offset = 0
py> if time.daylight:
py. offset = time.altzone
py. else:
py. offset = time.timezone
py.
py> print offset
-7200
py>

You can use time.time() to get the UTC time, then add the offset.
 
P

Peter Kleiweg

(e-mail address removed) schreef op de 6e dag van de hooimaand van het jaar 2005:
You can calculate the offset of where you are like this:

martin@ubuntu:~ $ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> import time
py> offset = 0
py> if time.daylight:
py. offset = time.altzone
py. else:
py. offset = time.timezone
py.
py> print offset
-7200
py>

You can use time.time() to get the UTC time, then add the offset.

The offset is for this moment, not for the date and time of the
string parsed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,701
Latest member
XavierQ83

Latest Threads

Top