問題描述
我怎樣才能真正為下一個(gè) 6 點(diǎn)鐘創(chuàng)建時(shí)間戳,無論是今天還是明天?
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)換為時(shí)間戳.
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 點(diǎn)生成時(shí)間戳,您可以使用類似以下內(nèi)容.這將創(chuàng)建一個(gè)表示當(dāng)前時(shí)間的 datetime 對(duì)象,檢查當(dāng)前時(shí)間是否 <6點(diǎn)與否,為下一個(gè)6點(diǎn)創(chuàng)建一個(gè)datetime對(duì)象(包括必要時(shí)增加天數(shù)),最后將datetime對(duì)象轉(zhuǎn)換為時(shí)間戳
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)于如何將明天(在特定時(shí)間)日期轉(zhuǎn)換為時(shí)間戳的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!