Tengis
Tengis

Reputation: 2809

converting time to seconds and back

I have a date (I suppose it is in UTC, but may also be in localtime) I would like to convert this date to seconds ... and back (seconds --> date)

So, after some research in Stackoverflow I came up with those two functions:

def UTC_to_sec(utc_time):
    """
    convert time in UTC to seconds. 
    input: s string
    output: float
    """
    return time.mktime( datetime.datetime.strptime(utc_time, "%Y-%m-%d %H:%M:%S").timetuple() )

def sec_to_UTC(s):
   """
    convert time in to seconds  to UTC.  
    input: time in seconds (float)
    output: string

    """
   return datetime.datetime.utcfromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')

# test with mydate="2010-09-15 08:31:00"
print "time ", mydate, " (UTC) --> (",UTC_to_sec(maydate), ") [s] --> ",sec_to_UTC(UTC_to_sec(mydate)), " (UTC)"

The result is:

time 2010-09-15 08:31:00 (UTC) --> ( 1284532260.0 ) [s] --> 2010-09-15 06:31:00 (UTC)

Does this mean mydate was in localtime and not in UTC?

I only get the correct result when modifying the function sec_to_UTC() as follows:

datetime.datetime.utcfromtimestamp(s-time.altzone).strftime('%Y-%m-%d %H:%M:%S')

time.altzone being in my case -7200 [s]. But this is a nasty workaround.

My question is: What makes the aforementioned date-seconds-date conversion depends on the timezone?

Upvotes: 1

Views: 180

Answers (1)

unwind
unwind

Reputation: 399743

The culprit is time.mktime().

From the documentation:

This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC.

Upvotes: 1

Related Questions