使用 datetime 库获取时间。
获取当前时间:
import datetime
print(datetime.datetime.now())
. 后面的是微秒,也是一个时间单位,1秒=1000000微秒。
转为时间戳:
import datetime
date = datetime.datetime.now()
timestamp = date.timestamp()
print(timestamp)
获取十位时间戳:
import datetime
date = datetime.datetime.now()
timestamp = int(date.timestamp())
print(timestamp)
获取十三位时间戳:
import datetime
date = datetime.datetime.now()
timestamp = int(date.timestamp()*1000)
print(timestamp)
获取特定时间的时间戳(比如获取00:00:00时刻的时间戳):
import datetime
date = datetime.datetime.now()
begin_time = date.replace(hour=0, minute=0, second=0, microsecond=0)
timestamp = int(date.timestamp())
print(timestamp)
date.replace() 输入的参数可以替换当前date中的值,year, month, day, hour, minute, second, microsecond
获取十位的话只需要替换 hour,minute,second 就可以,如果是获取十三位,还需要替换microsecond,否则会获取到当前时间的微秒。
获取十三位没有替换microsecond:
获取十三位替换microsecond:
(获取23:59:59时刻的时间戳):获取十三位时也需要替换microsecond
import datetime
date = datetime.datetime.now()
begin_time = date.replace(hour=0, minute=0, second=0, microsecond=0)
timestamp = int(begin_time.timestamp() * 1000)
end_time = date.replace(hour=23, minute=59, second=59, microsecond=999999)
end_timestamp = int(end_time.timestamp() * 1000)
print(timestamp)
print(end_timestamp)
将microsecond替换为 999999