#!/usr/bin/env python import time import pytz import datetime from tzlocal import get_localzone from dm.common.exceptions.invalidArgument import InvalidArgument class TimeUtility: UTC_MINUS_LOCAL_TIME = None @classmethod def getCurrentGMTimestamp(cls): """ Formats GMT timestamp. """ return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time())) @classmethod def formatGMTimestamp(cls, t): """ Format GMT timestamp. """ return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(t)) @classmethod def getCurrentLocalTimestamp(cls): """ Formats local timestamp. """ return time.strftime('%Y/%m/%d %H:%M:%S %Z', time.localtime(time.time())) @classmethod def formatLocalTimestamp(cls, t): """ Formats local timestamp. """ return time.strftime('%Y/%m/%d %H:%M:%S %Z', time.localtime(t)) @classmethod def toDateTime(cls, t, format): if not t: return None tz = get_localzone() try: dt = datetime.datetime.strptime(t, format) except Exception, ex: raise InvalidArgument('Cannot parse input: %s' % ex) return tz.localize(dt, is_dst=None) @classmethod def utcToLocalTime(cls, utc): if cls.UTC_MINUS_LOCAL_TIME is None: cls.UTC_MINUS_LOCAL_TIME = (datetime.datetime.utcnow()-datetime.datetime.now()).total_seconds() if cls.UTC_MINUS_LOCAL_TIME > 0: cls.UTC_MINUS_LOCAL_TIME = int(cls.UTC_MINUS_LOCAL_TIME+0.5) else: cls.UTC_MINUS_LOCAL_TIME = int(cls.UTC_MINUS_LOCAL_TIME-0.5) localTime = utc - cls.UTC_MINUS_LOCAL_TIME return localTime ####################################################################### # Testing. if __name__ == '__main__': print TimeUtility.toDateTime('2015-01-03', '%Y-%m-%d') dt0 = datetime.datetime.utcnow() dt1 = datetime.datetime.now() ts0 = time.mktime(dt0.timetuple()) ts1 = time.mktime(dt1.timetuple()) t0 = time.strftime("%Y/%m/%d %H:%M:%S", dt0.timetuple()) print 'UTC: ', t0, ts0 t1 = time.strftime("%Y/%m/%d %H:%M:%S", dt1.timetuple()) print 'LOCAL: ', t1, ts1 print 'UTC TO LOCAL: ', TimeUtility.utcToLocalTime(ts0)