如何将明天(在特定时间)日期转换为时间戳

时间:2023-04-17
本文介绍了如何将明天(在特定时间)日期转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我怎样才能真正为下一个 6 点钟创建时间戳,无论是今天还是明天?

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 替换一天,但我无法将其转换为时间戳.

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 点生成时间戳,您可以使用类似以下内容.这将创建一个表示当前时间的 datetime 对象,检查当前时间是否 <6点与否,为下一个6点创建一个datetime对象(包括必要时增加天数),最后将datetime对象转换为时间戳

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)

这篇关于如何将明天(在特定时间)日期转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 matplotlib 中绘制一天中的时间与日期 下一篇:如何在 Pandas 中转换 datetime 列的时区?

相关文章