简体   繁体   English

在Python中,将一天中的特定时间与当前时间相比较

[英]In Python, compare a specific time on a day with the current time in epoch

I am attempting to compare the current time (A) to a certain time (B) on the current day. 我正在尝试将当前时间(A)与当天的特定时间(B)进行比较。 Subsequently, based on the result of that comparison, I want to return the POSIX time for a specific time, either tomorrow (C) or the day after tomorrow (D). 随后,基于比较的结果,我想返回特定时间(明天(C)或后天(D))的POSIX时间。

To illustrate, an example: 举例说明:

Suppose we have the current time (A) to be 12:00. 假设当前时间(A)为12:00。 I want to compare that to (B), which is 20:00 today. 我想将其与今天的20:00(B)进行比较。

Since A < B, I want to return 13:00 tomorrow, formatted as a POSIX time. 由于A <B,我想明天返回13:00,格式为POSIX时间。

Another example: 另一个例子:

Now suppose the current time (A) is 21:00. 现在假设当前时间(A)为21:00。 I still want to compare that to (B), which is 20:00 today. 我仍然想将其与今天的20:00(B)进行比较。

Since A > B, I want to return 13:00 the day after tomorrow, again formatted as a POSIX time. 由于A> B,因此我想后天返回13:00,再次将其格式化为POSIX时间。

I've been trying to make this work using the time and datetime libraries, but when using time I have a hard time finding B and when using datetime I can't find a way to return C and D as a POSIX time. 我一直在尝试使用timedatetime time库来完成这项工作,但是当使用time我很难找到B,而当使用datetime时间时,我找不到一种将C和D作为POSIX时间返回的方法。

Have I correctly identified which libraries I should use and if so, what am I missing? 我是否正确确定了我应该使用哪些库?如果是,我缺少什么?

There are two questions: 有两个问题:

  • Find whether you need "13:00 tomorrow" or "13:00 the day after tomorrow" depending on the current time relative to 20:00 根据相对于20:00的当前时间,查找是否需要“明天13:00” 后天 13:00”
  • Convert the result eg, "13:00 tomorrow" to POSIX time 将结果(例如“明天13:00”)转换为POSIX时间

The first one is simple: 第一个很简单:

#!/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))

Note: 00:00 is considered to be less than 20:00 . 注意: 00:00 : 00:00被认为小于20:00 You might want to use time intervals instead eg, 20:00-8:00 vs. 8:00-20:00 , to find out whether the current time is in between . 您可能想改用时间间隔,例如20:00-8:008:00-20:00 ,以查明当前时间是否在之间


The second question is essentially the same as How do I convert local time to UTC in Python? 第二个问题与如何在Python中将本地时间转换为UTC基本上相同 In the general case, there is no exact answer eg, the same local time may occur twice or it may be missing completely—what answer to use depends on the specific application. 在一般情况下,没有确切的答案,例如,相同的本地时间可能会出现两次,或者可能完全丢失-使用哪种答案取决于特定的应用程序。 See more details in my answer to python converting string in localtime to UTC epoch timestamp . 请参阅我在python将本地时间将字符串转换为UTC纪元时间戳的答案中的更多详细信息。

To get the correct result taking into account possible DST transitions or other changes in the local UTC offset between now and the target time (eg, "the day after tomorrow"): 为了获得正确的结果,并考虑到现在和目标时间之间可能存在的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()

Note: is_dst=None is used to assert that the given local time exists and unambiguous eg, there is no DST transitions at 13:00 in your local time. 注意: is_dst=None用于断言给定的本地时间是否存在并且是明确的,例如,本地时间13:00处没有DST转换。

If time.mktime() has access to a historical timezone database on your platform (or you just don't care about changes in the local utc offset) then you could find the "epoch" time using only stdlib: 如果time.mktime()可以访问您平台上的历史时区数据库(或者您根本不在乎本地utc偏移量的变化),则可以仅使用stdlib查找“时代”时间:

import time

unix_time = time.mktime(target_time.timetuple())

You can read more details on when it fails and how to workaround it in Find if 24 hrs have passed between datetimes - Python . 您可以在“ 查找日期时间之间是否经过24小时-Python”中阅读有关何时失败以及如何解决该问题的更多详细信息。

Or more than you probably wanted to know about finding POSIX timestamp in Python can be found in Converting datetime.date to UTC timestamp in Python . 或者,在Python中将datetime.date转换为UTC时间戳,可以找到比在Python中查找POSIX时间戳更多的信息。

import datetime

A = datetime.datetime.now()
# A = A.replace(hour=21, minute=5)  # This line simlulates "after 21:00"
B = A.replace(hour=20, minute=0, second=0, microsecond=0)  # 20:00 today

if A < B:
    print A.replace(hour=13, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1)  # 13:00 tomorrow
else:
    print A.replace(hour=13, minute=0, second=0, microsecond=0) + datetime.timedelta(days=2)  # 13:00 the day after

in Python 3 you can then return 在Python 3中,您可以返回

X.timestamp()

in Python 2 you can use 在Python 2中,您可以使用

def timestamp(dt):
    return (dt - datetime.datetime(1970, 1, 1)).total_seconds()

timestamp(X)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM