我们知道,要获取现在的时间可以使用Python自带的 datetime
来实现:
import datetime
now = datetime.datetime.now()
如果要获得现在这一秒钟的时间戳,可以继续加一行:
import datetime
now = datetime.datetime.now()
ts = now.timestamp()
那么问题来了,如何生成今天0点的时间戳?
可能有人会这样写:
import datetime
now = datetime.datetime.now()
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond
midnight = now - datetime.timedelta(hours=hour) - datetime.timedelta(minutes=minute) - datetime.timedelta(second=second) - datetime.timedelta(microsecond=microsecond)
midnight_ts = midnight.timestamp()
那么有没有稍微简单一点的办法呢?可能还有一些人会这样写:
import datetime
now = datetime.datetime.now()
midnight_str = now.strftime('%Y-%m-%d 00:00:00')
midnight = datetime.datetime.strptime(midnights_str, '%Y-%m-%d %H:%M:%H')
midnight_ts = midnight.timestamp()
这样写虽然代码少了,但是由于对象转成了字符串又从字符串转成对象,效率降低了。
当然,还可能有人会从now对象里面拿出年月日,然后再通过调用datetime手动生成今天0点datetime对象。。。
方法很多,但是实际上,datetime自带了一个替换时分秒的功能:
import datetime
now = datetime.datetime.now()
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
midnight_ts = midnight.timestamp()