Python 获取今天任意时刻的时间戳
是大嘟嘟呀 人气:0代码
# -*- coding: utf-8 -*- # Author : markadc from datetime import datetime, timedelta # 获取今天任意时刻的时间戳 def today_anytime_tsp(hour, minute, second=0): now = datetime.now() today_0 = now - timedelta(hours=now.hour, minutes=now.minute, seconds=now.second) today_anytime = today_0 + timedelta(hours=hour, minutes=minute, seconds=second) tsp = today_anytime.timestamp() print('{} 的时间戳是 {}'.format(today_anytime, tsp)) return tsp if __name__ == '__main__': tsp = today_anytime_tsp(18, 15, 23) # 获取今天18点15分23秒的时间戳 print(tsp)
输出
ps:Python来获取昨天和今天的日期
这个问题也是常见问题,可能碰到这种问题我们就会这么写yesterday = today - 1,tomorrow = today + 1;这样写实际会报错,会提示不支持的操作类型。碰到时间差的问题的,优先考虑datetime模块中的timedelta。具体获取很简单
>>> import datetime >>> today = datetime.date.today() # 今天 >>> yesterday = today - datetime.timedelta(days=1) # 昨天 >>> tomorrow = today + datetime.timedelta(days=1) # 明天 >>> print(yesterday,today,tomorrow) (datetime.date(2018, 7, 31), datetime.date(2018, 8, 1), datetime.date(2018, 8, 2)) >>>
其他的也可以获取一秒后,一分钟,一小时,甚至一年的具体日期
>>> import datetime >>> t1 = datetime.datetime.today() # 获取现在时间 >>> t1 datetime.datetime(2018, 8, 1, 21, 34, 19, 924000) >>> t2 = t1 + datetime.timedelta(seconds=1) # 获取一秒后的时间 >>> t2 datetime.datetime(2018, 8, 1, 21, 34, 20, 924000) >>> t3 = t1 + datetime.timedelta(seconds=60) # 获取一分后的时间 >>> t3 datetime.datetime(2018, 8, 1, 21, 35, 19, 924000) >>> t4 = t1 + datetime.timedelta(seconds=3600) # 获取一小时后的时间 >>> t4 datetime.datetime(2018, 8, 1, 22, 34, 19, 924000) >>> today = datetime.date.today() # 获取当前日期 >>> anday = today + datetime.timedelta(days=365) # 获取一年后日期 >>> print(anday) 2019-08-01 >>>
加载全部内容