Friday, February 28, 2014

Be careful about local time and UTC time when converting Date time to Unix time

In the last post, I paste my python script about converting from local time to UTC time and vice versa.
The reason is I made a mistake when convert Date time to Unix time(Not local time to UTC or UTC to local time).  I treated local time as UTC time and got the wrong results.

Here is the comparison of the correct way and the wrong way:
You can see the below python code, input is "2013-08-23 10:00:00", '%Y-%m-%d %H:%M:%S' which is the same for two converters, but the result in Unix time is DIFFERENT!


>>> calendar.timegm((datetime.datetime.strptime("2013-08-23 10:00:00", '%Y-%m-%d %H:%M:%S')).utctimetuple())
1377252000
>>> int(str(time.mktime(datetime.datetime.strptime("2013-08-23 10:00:00", '%Y-%m-%d %H:%M:%S').utctimetuple()) )[:-2])
1377277200




Why?
The reason is calendar.timegm(t) takes a UTC time as input, and time.mktime(t) takes a local time as input! So simple methods, but it took me way way too long time to find out what exactly happens! 


Here's the python script:

import sys
import datetime
import time
import calendar

#date format 
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
#hours offset from UTC 
TIME_OFFSET_TO_UTC = 0


#Converts date time to Unix time
def date_to_unix(date_time):
 delta = datetime.timedelta(0,0,0,0,0,TIME_OFFSET_TO_UTC,0)
 return calendar.timegm((datetime.datetime.strptime(date_time, TIME_FORMAT) - delta).utctimetuple())
date_to_unix("2014-02-28 16:24:00")

Python local time and UTC time conversion

This python script is to show how to get Local time and UTC time, and how to convert Local time to UTC time and vice versa.

Two methods should attract more attention. time.mktime(t) and calendar.timegm(t).
time.mktime(t)  pass local time as a input and calendar.timegm(t)'s t is UTC time. The below is from python doc.

Therefore, when I convert local time to UTC time, I used time.mktime(t), and when I convert UTC to local time, I used calendar.timegm().

There're tons of ways to convert local time and UTC, the below script is one of all choices.

time.mktime(tThis 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. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.
calendar.timegm(tupleAn unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.




#!/usr/bin/python
import calendar
import datetime
import time

TIME_FORMAT = '%Y-%m-%d %H:%M:%S'

#Gets local time in given format
def get_current_local_time():
        local = datetime.datetime.now()
        print "Local:", local.strftime(TIME_FORMAT)


#Gets UTC time in given format
def get_current_utc_time():
        utc = datetime.datetime.utcnow()
        print "UTC:", utc.strftime(TIME_FORMAT)


#Converts local time to UTC time
def local_2_utc():
        local = datetime.datetime.now().strftime(TIME_FORMAT)
        print "local_2_utc: before convert:", local
        timestamp =  str(time.mktime(datetime.datetime.strptime(local, TIME_FORMAT).timetuple()) )[:-2]
        utc = datetime.datetime.utcfromtimestamp(int(timestamp))
        print "local_2_utc: after convert:", utc


#Converts UTC time to local time
def utc_2_local():
        utc = datetime.datetime.utcnow().strftime(TIME_FORMAT)
        print "utc_2_local: before convert:", utc
        timestamp =  calendar.timegm((datetime.datetime.strptime( utc, TIME_FORMAT)).timetuple())
        local = datetime.datetime.fromtimestamp(timestamp).strftime(TIME_FORMAT)
        print "utc_2_local: after convert:", local


#Invokes methods
get_current_local_time()
get_current_utc_time()
local_2_utc()
utc_2_local()



Friday, February 21, 2014

Sublime Text --- Visible white-space(indentation) characters

 People use Geany knows that user can configure "show white space" to display the indentation spaces, it is really helpful for developers to view source codes like python.

It looks like this:


This feature  can be configured in Sublime Text as well. Choose Preference, then Settings-Default and past the below json configuration:

{
"font_size": 10,
"draw_white_space": "all"
}

Reference: link here
Then the source code in Sublime will look like this: