我需要在六小時前的時間之前獲取最近的中午 UTC 或午夜 UTC 的時間(以秒為單位)。換句話說,如果當前是 2022-05-17 04:00:00,我希望回傳值 2022-05-16 12:00:00(2022-05-17 04:00:00 之前的六個小時是2022-05-16 22:00:00,因此最近的中午/午夜是 2022-05-16 12:00:00)。
我目前正在抓取datetime.now(),datetime.timedelta()用于回傳六個小時,抓取小時并使用條件設定午夜與中午,將其全部組合成一個字串,然后datetime.strptime()用于轉換回日期時間物件,另一個datetime.timedelta()用于檢查時代,最后datetime.total_seconds()。我認為必須有一種更優雅的方式,我將非常感謝有關縮短此代碼的建議(盡管它確實有效):
from datetime import datetime, timedelta
now = datetime.now()
six_hours_ago = now-timedelta(hours = 6)
six_hours_ago_date = six_hours_ago.date()
six_hours_ago_hour = six_hours_ago.hour
if six_hours_ago_hour < 12:
gribtime_to_search = '00:00'
else:
gribtime_to_search = '12:00'
gribdate_string_to_search = f"{str(six_hours_ago_date)} {gribtime_to_search}"
gribdatetime_to_search = datetime.strptime(gribdate_string_to_search, "%Y-%m-%d %H:%M")
epoch_timedelta = gribdatetime_to_search - datetime(1970, 1, 1)
seconds = epoch_timedelta.total_seconds()
uj5u.com熱心網友回復:
一種更簡單的方法是使用datetime.combine將物件組合date成time(時區感知)日期時間,如下所示。
我還會確保使用和with引數之datetime類的方法,這樣您就可以確保您使用的是 UTC 日期和時間。utcnow()replace()tzinfo
from datetime import datetime, timedelta, time, timezone
# now = datetime.utcnow()
now = datetime.fromisoformat('2022-05-17 04:00:00').replace(tzinfo=timezone.utc)
print('Input:', now)
six_hours_ago = now - timedelta(hours=6)
six_hours_ago_date = six_hours_ago.date()
six_hours_ago_hour = six_hours_ago.hour
time_to_set: time = time.min if six_hours_ago_hour < 12 else time(hour=12)
# combine `date` and `time` into a UTC `datetime`
dt = datetime.combine(six_hours_ago_date, time_to_set, timezone.utc)
# get unix timestamp
seconds = round(dt.timestamp())
print('Result:', dt)
print('Epoch ts:', seconds)
結果:
Input: 2022-05-17 04:00:00 00:00
Result: 2022-05-16 12:00:00 00:00
Epoch ts: 1652702400
uj5u.com熱心網友回復:
在您計算后,我可能會執行以下操作six_hours_ago:
six_hours_ago_midnight = datetime.combine(six_hours_ago, datetime.min.time())
if six_hours_ago - six_hours_ago_midnight >= timedelta(hours=12):
return six_hours_ago_midnight timedelta(hours=12)
else:
return six_hours_ago_midnight
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479584.html
標籤:Python python-3.x 约会时间 蟒蛇日期时间
下一篇:Kotlin-型別引數的輸出型別
