How to know time difference even if you pass midnight ? python - python

So the idea behind this is quite simple(yes it is an excercise not quite a real life problem)
So there is this girl who's clock is false but her friends clock is always right. so as she leaves from home she remembers the time she left her clock. at her friends she sees the time she arrives and she leaves and once home she sees the time again. This way even if we don't know how long she drove we can know the right time.
E.g she leaves at 6:32 at her place she arrives with her friends at 14:14 and leaves with her friend at 17:21 and arrives home at 13:29.
The total time gone is 6:57 of which she spend 3:07 with her friends the rest of the time is divided by 2 so you know the time of 1 car trip.
so if you add up this time with the time you left at the friends house you find the actual time.
Now I have solved this problem before but I didn't knew the datetime function back then so I figured maybe I could solve it that way. My trouble with datetime is that when midnight passes it is stuck
For example when she leaves at home at 9:04 arrives at friend by 6:15 and leaves at 14:54 to be back home at 5:13 I get that the correct time is 8:57 while it should be 20:57.
Maybe it is someting in my datetime.timedelta but I don't kknow how to work around.
Any suggestions are very welcome
Thanks a lot
My code on this moment:
import datetime
# function nessesary to convert timedelta back into time
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return hours, minutes, seconds
# input
hour_department_home = int(input("Hour of department at home: "))
minutes_department_home = int(input("Minutes of department at home: "))
hour_arrival_friend = int(input("Hour of arrivel friends house: "))
minutes_arrival_friend = int(input("Minutes of department friends house: "))
hour_department_friend = int(input("Hour of arrivel friends house: "))
minutes_department_friend = int(input("Minutes of arrivel friends house: "))
hour_arrival_home = int(input("Hour of arrivel home : "))
minutes_arrival_home = int(input("Minutes of arrivel home: "))
# putting into hours
department_home = datetime.time(hour_department_home,minutes_department_home,second=0)
arrival_friend = datetime.time(hour_arrival_friend,minutes_arrival_friend)
department_friend = datetime.time(hour_department_friend,minutes_department_friend)
arrival_home= datetime.time(hour_arrival_home,minutes_arrival_home)
# time at friends
uur_1,uur_2 = datetime.timedelta(hours=department_friend.hour),datetime.timedelta(hours = arrival_friend.hour)
hours_with_friend = uur_1-uur_2
min_1,min_2= datetime.timedelta(minutes=department_friend.minute),datetime.timedelta(minutes=arrival_friend.minute)
min_with_friend = min_1-min_2
total_time_with_friend = hours_with_friend + min_with_friend
# time away
uur_1h,uur_2h = datetime.timedelta(hours=arrival_home.hour),datetime.timedelta(hours = department_home.hour)
hours_away_from_home = uur_1h-uur_2h
min_1h,min_2h= datetime.timedelta(minutes=arrival_home.minute),datetime.timedelta(minutes=department_home.minute)
min_away_from_home = min_1h-min_2h
total_time_away = hours_away_from_home + min_away_from_home
duration_drive = (total_time_away-total_time_with_friend) /2
the_time = datetime.timedelta(hours=department_friend.hour,minutes=department_friend.minute) +duration_drive
hours, minutes, seconds = convert_timedelta(the_time)
print(hours)
print(minutes)

Use datetime.datetime instead of datetime.time, it will take into account the change of day
date_1 = datetime.datetime(year1, month1, day1, hour1, minutes1, seconds1)
date_2 = datetime.datetime(year2, month2, day2, hour2, minutes2, seconds2)
timedelta = date_2 - date_1
and then you have timedelta.seconds, timedelta.days, timedelta.microseconds and timedelta.total_seconds() if you need a floating number

Related

How to run python script on start up of pc but only once in day?

I have created a python script which do birthday wish to a person automatically when birthdate is arrive. I added this script on window start up but it run every time when i start my pc and do birthday wish to person also. I want to run that script only once a day. What should i do?
Try this at the start of the file:
import datetime
actualday = datetime.datetime.today().day # get the actual day
actualmonth = datetime.datetime.today().month # get the actual month
bday = 1 # day of birthday
bmonth = 1 # month of birthday
if actualday == bday and actualmonth == bmonth :
# code
it should finish the process if the dates aren't equal
You can run this program when the system boot How to start a python file while Windows starts?
And after that, you need check the time of when the system started like:
import datetime
dayToday = datetime.datetime.today().day
monthToday = datetime.datetime.today().month
birthdayDay = 1
birthdayMonth = 10
if dayToday == birthdayDay and monthToday == birthdayMonth:
print "HPBD"

How to automate control of Wemo light switch based on iPhone GPS

I'm writing a program to toggle the lights at my house based on my iPhone's GPS coordinates. Below is what I have so far. However, I feel like there must be a better way to do this. Is there a way to get GPS data without pinging my phone every five minutes?
So far I've tried the following with no joy:
Using Shortcuts and Scriptable I tried to write some JavaScript that would trigger when I got close to home. However, I could not figure out how to use await require('wemo-client') using scriptablify. I kept getting an error, "ReferenceError: Can't find variable: require".
IFTTT does not have a variable timed trigger so the lights won't turn off after 15 minutes. Also, I plan on adding a motion sensor trigger that is unsupported.
Pythonista is $10. Yes, I am that cheap.
Apple HomeKit does not support the model I'm using, Wemo Smart Light Switch F7C030.
The code below works, but I hate that I have to ping my phone every five minutes. I'd rather save battery life by firing this code once or twice a day, as needed.
Any suggestions would be greatly appreciated.
Code:
import sys
import time
import datetime
import os
from pyicloud import PyiCloudService
import pywemo
APPLE_ID = os.getenv('APPLE_ID') # Apple ID username
APPLE_ID_PASSWORD = os.getenv('APPLE_ID_PASSWORD') # Apple ID password
API = PyiCloudService(APPLE_ID, APPLE_ID_PASSWORD)
IPHONE = API.devices[1]
LOCATION = IPHONE.location()
FIVE = 300 # 5 * 60 seconds
FIFTEEN = 900 # 15 * 60 seconds
ONEMILE = 0.01449275362318840579710144927536 # one mile is 1/69 degrees lat or long
HOMELAT = # my home's latitude
HOMELONG = # my home's longitude
WEMOS = pywemo.discover_devices()
LEN_WEMOS = range(len(WEMOS))
# Two factor authentication to retrieve iPhone data
if API.requires_2fa:
import click
print("Two-step authentication required. Your trusted devices are:")
DEVICES = API.devices
for i, device in enumerate(DEVICES):
print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber'))))
DEF_DEVICE = click.prompt('Which device would you like to use?', default=0)
DEVICE = DEVICES[DEF_DEVICE]
if not API.send_verification_code(DEVICE):
print("Failed to send verification code")
sys.exit(1)
CODE = click.prompt('Please enter validation code')
if not API.validate_verification_code(DEVICE, CODE):
print("Failed to verify verification code")
sys.exit(1)
# Turn off the lights when I leave
def leavehome():
timenow = datetime.datetime.now()
print("Left home on {}".format(timenow.strftime("%B %d, %Y at %H:%M:%S")))
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Turn on the lights for 15 minutes when I get home
def arrivehome():
timenow = datetime.datetime.now()
print("Arrived home on {}".format(timenow.strftime("%B %d, %Y at %H:%M:%S")))
# Loop through all Wemo devices
for wemo in LEN_WEMOS:
WEMOS[wemo].on()
time.sleep(FIFTEEN)
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Automatically turn off the lights after 15 minutes - save electricity
def timeoff():
time.sleep(FIFTEEN)
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Ping my phone for GPS data
def pingphone(prev):
mylat = LOCATION["latitude"]
mylong = LOCATION["longitude"]
logic(prev, mylat, mylong)
time.sleep(FIVE)
# Perform logic to determine if I'm home, out, arriving, or leaving
def logic(prev, lat, long):
inrange = (HOMELAT+ONEMILE >= lat >= HOMELAT-ONEMILE and HOMELONG+ONEMILE >= long >= HOMELONG-ONEMILE)
current = bool(inrange)
previous = prev
if current and not previous:
arrivehome()
elif previous and not current:
leavehome()
else:
timeoff()
pingphone(current)
# Run the script
pingphone(False)

Adding user time in python 3

Hi Everyone i have googles to my hearts content but have not found the answer.
Basically I want to add user inputted time to the current time.
This is just a small project I'm working on while learning Python.
So if the current time is 17:16 and the user wants to add 1hr 30 to that. how would i do it.
This is what i have:
import datetime
flex = input("Enter your flex amount in HHMM:")
flex = flex[0]+flex[1]+"-"+flex[2]+flex[3]
time = datetime.datetime.now().strftime("%H-%M")
balance = time+flex
print(time)
print(flex)
print(balance)
I have now tried
import datetime
flex = input("Enter your flex amount in HHMM:")
time = datetime.datetime.now().strftime("%H-%M")
flex = flex[0]+flex[1]+"-"+flex[2]+flex[3]
time = time[0]+time[1]+"-"+time[2]+time[3]
balance = datetime.timedelta(hours=int(time[0]+time[1]),
minutes=int(time[2]+time[3]) +
datetime.timedelta(hours=int(flex[0]+flex[1]),
minutes=int(flex[2]+flex[3]))
But now its complaining about its expecting an integer. but if i change it ot an integer will that not defeat the purpose of me wanting to add is as time.
Thanks
I got it to work using the answer. This is what it looks like now thanks pal.
from datetime import timedelta as td
import datetime as da
#flex = input("Enter your flex amount in HHMM:")
flex = "0134"
now = da.datetime.now()
user_hours = int(flex[:2])
user_minute = int(flex[2:5])
delay = td(hours=user_hours, minutes=user_minute)
balance = da.datetime.now()+delay
print("Lunch: " +str(lunch))
print("Time when balance at 00:00 : " +str(balance))
print("Now: " +str(now))
Simple using timedelta create an offset indicated by timedelta object and ad it to your time object (working the same with date and datetime too).
from datetime import timedelta, datetime
actual_time = datetime.now()
user_hours = int(flex[:3])
user_minute = int(flex[2:5])
delay = timedelta(hours=user_hours, minutes=user_minute)
print(datetime.now()+delay)
So if the current time is 17:16 and the user wants to add 1hr 30 to
that. how would i do it.
You can use timedelta, i.e.:
new_time = datetime.datetime.now() + datetime.timedelta(hours=1, minutes=30) # or simply minutes=90, etc...
Cool so when tring
balance = datetime.timedelta(hours=int(time[0]+time[1]), minutes=int(time[2]+time[3]) + datetime.timedelta(hours=int(flex[0]+flex[1]), minutes=int(flex[2]+flex[3]))
its complaining that its expecting an interger not a time delta

User-specific date countdown

I am new here and I was hoping someone could help me out with a project I'm attempting to create. Using Python I would like to make a countdown clock from user-specific information that, when getting a month day and year, would finish by printing an active countdown clock for that specific date. Is this possible? If so, how?
Thanks in advance.
-Anthony
The code below can be a start. The function date_countdown takes in a date string and a date format corresponding to the date string, and outputs a countdown to the terminal.
countdown.py
import datetime
def date_countdown(future_datetime, date_format):
print("Countdown for {}:".format(future_datetime))
seconds_left = -1
while seconds_left:
cur = datetime.datetime.now()
fut = datetime.datetime.strptime(future_datetime, date_format)
left = fut - cur
print(
"{0: >3d} days, {1:0>2d}:{2:0>2d}:{3:0>2d}".format(
left.days, # days
left.seconds // 3600, # hours
(left.seconds // 60) % 60, # minutes
(left.seconds % 60) # seconds
),
end='\r')
time.sleep(1)
seconds_left = left.total_seconds()
print('Done!')
date_countdown('2018-12-25', '%Y-%m-%d')
Output:
Countdown for 2018-12-25:
27 days, 04:15:40

Testing how long a user has been in a list

I'm using a bot for twitch and it tracks the time the user has spent in the channel. !time You have spent 10 seconds in the stream. However when multiple users use this command !time it doesn't have a seperate 'count' for each user. Ex:
Rustie: !time
Bot: Rustie, you have 20 seconds in the stream.
~1 minute later~
John: !time
Bot: John, you have 1 minute 20 seconds in the stream.
My current code:
usersForTime = []
if "time" in message:
if user in usersForTime:
endTime = time.time() # I already made startTime in the !start command (which starts the time tracker in the first place)
ellapsed = (endTime - startTime)
sendMessage(s, user + ", you have " + "%.2f" % round(ellapsed, 2) + " seconds in the stream.")
else:
sendMessage(s ,"You need to start tracking your time with the !start command.")
You'll want to store startTime associated with a specific user, something like
userStart = {}
if user in usersForTime:
...
ellapsed = (endTime - userStart[user])
which uses a dictionary to look up the individual's startTime.
To store it originally (in !start):
userStart[user] = time.time()

Categories