最近,寫監控腳本需要 和 mysql 的13位時間戳 做對比:
python 2 & 3 通用
import datetime
import time
# 本機時間
hlocal = datetime.datetime.now()
# utc時間
hutc = datetime.datetime.utcnow()
# utc - 12 時間
hutc12 = datetime.datetime.utcnow()-datetime.timedelta(hours=12)
# utc 30 天
hutcday30 = datetime.timedelta(days=30)
# utc - 12h - 30d 格式化位時
hutc12h30d = (hutc12-hutcday30).strftime("%Y-%m-%d %H:00:00")
# 10位 時間戳
hutc12h30dtuple10w = int(time.mktime((time.strptime(hutc12h30d, "%Y-%m-%d %H:%M:%S"))))
# 13位時間戳
hutc12h30dtuple13w = int(time.mktime((time.strptime(hutc12h30d, "%Y-%m-%d %H:%M:%S"))) * 1000)
# 當前時間 - 15d
hlocal15 = datetime.datetime.now()-datetime.timedelta(days=15)
# 當前時間 - 15d 轉 毫秒級時間戳
hlocal15inttuple = (time.mktime(hlocal15.timetuple()) * 1000 + hlocal15.microsecond / 1000)
shell
# 獲取當前時間 / 毫秒精度
current=`date "+%Y-%m-%d %H:%M:%S"`
# 獲取當前時間 - 30d / 毫秒精度
current15d=`date -d -30days "+%Y-%m-%d %H:%M:%S"`
# 轉換毫秒時間戳
timeStamp=`date -d "$current" +%s`
currentTimeStamp=$((timeStamp*1000+`date "+%N"`/1000000))
echo $currentTimeStamp
mysql
mysql -u root -p'password' -e "SELECT REPLACE(unix_timestamp(current_timestamp(3)),'.','');"