問題描述
我怎樣才能真正為下一個 6 點鐘創(chuàng)建時間戳,無論是今天還是明天?
How can i actually create a timestamp for the next 6 o'clock, whether that's today or tomorrow?
我嘗試了 datetime.datetime.today() 并用 +1 和 hour = 6 替換一天,但我無法將其轉(zhuǎn)換為時間戳.
I tried something with datetime.datetime.today() and replace the day with +1 and hour = 6 but i couldnt convert it into a timestamp.
需要你的幫助
推薦答案
要為明天早上 6 點生成時間戳,您可以使用類似以下內(nèi)容.這將創(chuàng)建一個表示當(dāng)前時間的 datetime 對象,檢查當(dāng)前時間是否 <6點與否,為下一個6點創(chuàng)建一個datetime對象(包括必要時增加天數(shù)),最后將datetime對象轉(zhuǎn)換為時間戳
To generate a timestamp for tomorrow at 6 AM, you can use something like the following. This creates a datetime object representing the current time, checks to see if the current hour is < 6 o'clock or not, creates a datetime object for the next 6 o'clock (including adding incrementing the day if necessary), and finally converts the datetime object into a timestamp
from datetime import datetime, timedelta
import time
# Get today's datetime
dtnow = datetime.now()
# Create datetime variable for 6 AM
dt6 = None
# If today's hour is < 6 AM
if dtnow.hour < 6:
# Create date object for today's year, month, day at 6 AM
dt6 = datetime(dtnow.year, dtnow.month, dtnow.day, 6, 0, 0, 0)
# If today is past 6 AM, increment date by 1 day
else:
# Get 1 day duration to add
day = timedelta(days=1)
# Generate tomorrow's datetime
tomorrow = dtnow + day
# Create new datetime object using tomorrow's year, month, day at 6 AM
dt6 = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, 0, 0, 0)
# Create timestamp from datetime object
timestamp = time.mktime(dt6.timetuple())
print(timestamp)
這篇關(guān)于如何將明天(在特定時間)日期轉(zhuǎn)換為時間戳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!