简体   繁体   中英

Difference in seconds between timedate objects in Python

I have the following piece of code which would change me the background image on Windows 10 based on the actual time and date and sunset/sunrise time and date from an Excel spreadsheet.

from datetime import datetime
import pandas
import ctypes

file_path = "myfile.xlsx"
data = pandas.read_excel(file_path, header=0) #Header on line 0

#Today as day number in reference to 1st of Jan
day = datetime.now().timetuple().tm_yday

#Today's parameters
#sr and ss are column names in the Excel spreadsheet
#Minus 1 to account for 0 based indexing
**sunrise = data["sr"][day-1]
sunset = data["ss"][day-1]** 

#Time right now
**now = datetime.now().time()**

#Setting up the day_night variable depending on the now variable
if now > sunrise and now < sunset:
    day_night = 'day'
else:
    day_night = 'night'

#The path to the wallpapers being used
path = 'C:\\wallpapers\\'+ day_night +'.jpg'
SPI_SETDESKWALLPAPER = 20

#Function to change the wallpaper
def changeBG(path):
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path, 3) #SystemParametersInfoW for x64 architecture

changeBG(path)

Is there a way to calculate the time difference in seconds between now variable and sunrise or sunset variable? So far I tried a simple subtraction like print (now-sunset) and it would return me an error like this one:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-c713ddbffa2f> in <module>
     18 now = datetime.now().time()
     19 
---> 20 print (now-sunset)

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

The most straightforward approach is to convert time to seconds manually:

from datetime import datetime, timedelta, time


def seconds_in_time(time_value: time):
    return (time_value.hour * 60 + time_value.minute) * 60 + time_value.second


# Examples of time objects
t1 = datetime.now().time()
t2 = (datetime.now() + timedelta(minutes=2)).time()

print(seconds_in_time(t2) - seconds_in_time(t1))  # 120

Not sure there is a better way, as far as you work with time objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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