python 时间操作
年华似水,匆匆而过,整理一下这段时间的代码
class TimeClass: def __init__(self): self.time_handler = datetime.datetime.now(tz="utc") def get_now_time(self, time_format): """ get the now time :param time_format: "YY-MM-dd" :return: """ return self.time_handler.strftime(time_format) def get_time_fragment(self, ret_flag): if ret_flag in "year": return self.time_handle.year elif ret_flag in "month": return self.time_handle.month elif ret_flag in "day": return self.time_handle.day elif ret_flag in "hour": return self.time_handle.hour elif ret_flag in "minute": return self.time_handle.minute elif ret_flag in "second": return self.time_handle.second @staticmethod def get_interval_day_time(day, time_format): return_time = datetime.timedelta(day)+datetime.datetime.now() return return_time.strftime(time_format) @staticmethod def get_interval_minutes_time(minutes,time_format): return (datetime.datetime.now()+datetime.timedelta(minutes=minutes)).strftime(time_format) def get_interval_minutes_utc_time(self,minutes,time_format): return (datetime.datetime.utcnow()+datetime.timedelta(minutes=minutes)).strftime(time_format) def get_week_is_day(self): return self.time_handle.weekday() def str_transform_datetime(self,src_str,time_format): return datetime.datetime.strptime(src_str,time_format) def utc_switch_cst(self, src_time, ifornotdifferenceutc, time_format='%Y-%m-%d %H:%M:%S'): cst_time = datetime.datetime.now() utc_time = datetime.datetime.utcnow() utc_cst_difference = cst_time-utc_time src_time = datetime.datetime.strptime(src_time, time_format) if 'utc' == ifornotdifferenceutc: return (src_time - utc_cst_difference).strftime(time_format) elif 'cst' == ifornotdifferenceutc: return (src_time+utc_cst_difference).strftime(time_format)
uat-cst时间转换可以考虑用函数实现:
(datetime.datetime.utcnow() + datetime.timedelta(hours=8))