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(t) 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. 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(tuple) An 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()
Best post for handling time format and time zones.
ReplyDeleteThanks
Thanks man.It's handy.
ReplyDelete