涉及日期的常用方法,前几天、后几天、时间戳日期转换等
1.返回本地当前时间
def current_datetime(): """返回本地当前时间, 包含datetime 格式, 字符串格式, 时间戳格式(str) :return: (datetime 格式, 字符串格式, 时间戳格式) """ # 当前时间:datetime 格式 local_datetime_now = datetime.now() # 当前时间:字符串格式 local_strtime_now = datetime_to_strtime(local_datetime_now) # 当前时间:时间戳格式 13位整数 local_timestamp_now = datetime_to_timestamp(local_datetime_now) return local_datetime_now, local_strtime_now, local_timestamp_now
2.返回前第几天的时间
def before_now_datetime(days, fmt, now=None): """返回前第几天的时间, 包含datetime 格式, 字符串格式, 时间戳格式 :return: (datetime 格式, 字符串格式, 时间戳格式) """ if now != None: yestoday = now - timedelta(days=days) return yestoday.strftime(fmt) else: now = datetime.now() yestoday = now - timedelta(days=days) return yestoday.strftime(fmt)
3.返回后第几天的时间
def after_now_datetime(days, fmt, now=None): """返回后第几天的时间, 包含datetime 格式, 字符串格式, 时间戳格式 :return: (datetime 格式, 字符串格式, 时间戳格式) """ if now != None: yestoday = now + timedelta(days=days) return yestoday.strftime(fmt) else: now = datetime.now() yestoday = now + timedelta(days=days) return yestoday.strftime(fmt)
4.时间戳转普通时间
def timestamp_to_strtime(timestamp,fmt='%Y-%m-%d %H:%M:%S'): """将 10、13 位整数的毫秒时间戳转化成本地普通时间 (字符串格式) :param timestamp: 10、13 位整数的毫秒时间戳 (1456402864242) :return: 返回字符串格式 {str}'2016-02-25 20:21:04.242000' """ if not timestamp: return '' if len(str(timestamp)) == 13: timestamp = float(timestamp) / 1000.0 time_str = datetime.fromtimestamp(float(timestamp)).strftime(fmt) return time_str
def datetime_to_timestamp(datetime_obj): """将本地(local) datetime 格式的时间 (含毫秒) 转为毫秒时间戳 :param datetime_obj: {datetime}2016-02-25 20:21:04.242000 :return: 13 位的毫秒时间戳 1456402864242 string 格式 """ local_timestamp = str(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0) return local_timestamp
def strtime_to_datetime(timestr, fmt): """将字符串格式的时间 (含毫秒) 转为 datetiem 格式 :param timestr: {str}'2016-02-25 20:21:04.242' :return: {datetime}2016-02-25 20:21:04.242000 """ local_datetime = datetime.strptime(timestr, fmt) return local_datetime
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~