有两个问题:
- 根据相对于
20:00 的当前时间确定您是否需要“明天13:00” 或“后天13:00”
- 将结果例如 "13:00 tomorrow" 转换为 POSIX 时间
第一个很简单:
#!/usr/bin/env python
import datetime as DT
current_time = DT.datetime.now()
one_or_two = 1 if current_time.time() < DT.time(20, 0) else 2
target_date = current_time.date() + DT.timedelta(days=one_or_two)
target_time = DT.datetime.combine(target_date, DT.time(13, 0))
注意:00:00 被认为小于20:00。您可能希望使用时间间隔,例如,20:00-8:00 与 8:00-20:00,到 find out whether the current time is in between。
第二个问题与How do I convert local time to UTC in Python? 基本相同。在一般情况下,没有确切的答案,例如,相同的本地时间可能出现两次,也可能完全丢失——使用什么答案取决于具体的应用程序。在我对python converting string in localtime to UTC epoch timestamp 的回复中查看更多详细信息。
考虑到从现在到目标时间之间可能的 DST 转换或本地 UTC 偏移的其他变化(例如,“后天”),以获得正确的结果:
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
epoch = DT.datetime(1970,1,1, tzinfo=pytz.utc)
local_timezone = tzlocal.getlocalzone()
timezone_aware_dt = local_timezone.localize(target_time, is_dst=None)
posix_time = (timezone_aware_dt - epoch).total_seconds()
注意:is_dst=None 用于断言给定的本地时间存在且明确,例如,在您的本地时间 13:00 没有 DST 转换。
如果time.mktime() 可以访问您平台上的历史时区数据库(或者您只是不关心本地 UTC 偏移量的变化),那么您可以仅使用 stdlib 找到“纪元”时间:
import time
unix_time = time.mktime(target_time.timetuple())
您可以在Find if 24 hrs have passed between datetimes - Python 中阅读有关它何时失败以及如何解决它的更多详细信息。
或者更多关于在 Python 中查找 POSIX 时间戳的信息可以在Converting datetime.date to UTC timestamp in Python 中找到。