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
Related
I'm having issues with timezones and time offsets when working with Python, the Google Calendar API, and a client device operating in local time.
I have a Raspberry Pi which acts as a booking display outside a shared room. A Python script is called periodically to pull in the next upcoming calendar event from the Google Calendar API, split the result into variables, then pass those variables back to the bash script which called it.
I built it in the winter—when the UK's timezone has equivalence to UTC—and it worked perfectly. Now, in British Summer Time, it doesn't. The comparison of time objects to check whether or not the meeting is currently in progress doesn't work, and the room is showing as available when it isn't.
I've read and read (then re-read and re-read) articles and explainers about working with timezones and time offsets in Python, and I just cannot get my head around it. It doesn't help that I don't really understand object-based programming, so the example scripts provided don't mean much to me!
Ideally, I would simply like everything to work using local time. The Raspberry Pi is connected to the internet and its time is updated automatically, and the Google Calendar is correctly set to the UK timezone. How could I go about making all references to time 'local', so the time objects everywhere in the Python script are always current UK time?
Please help. Stack Overflow has been such a rich source of knowledge in the past that I've never needed to ask a question myself, but this is making my brain hurt! Thank you!
This is what I've got, which is a modified version of Google's own example script:
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
timeStamp_now = datetime.datetime.utcnow()
timeStamp_12 = timeStamp_now + timedelta(hours = 12)
now = timeStamp_now.isoformat() + 'Z' # 'Z' indicates UTC time
now12 = timeStamp_12.isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='################resource.calendar.google.com', timeZone="Europe/London", timeMin=now,
maxResults=1, singleEvents=True, showDeleted=False, timeMax=now12,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('meetingStart="NoEvents"')
for event in events:
startTime=event['start'].get('dateTime')
endTime=event['end'].get('dateTime')
eventTitle=event['summary']
eventOrganizer=event['creator'].get('email')
try:
eventConferencing=event['conferenceData'].get('conferenceSolution').get('name')
except:
eventConferencing=(' ')
if startTime <= now <= endTime:
inProgress=('true')
else:
inProgress=('false')
safeEventTitle= ""
for i in eventTitle:
num = ord(i)
if (num >=0) :
if (num <=127) :
safeEventTitle= safeEventTitle + i
print('meetingStart="' + startTime + '"')
print('meetingEnd="' + endTime + '"')
print('meetingTitle="' + safeEventTitle + '"')
print('meetingOrganizer="' + eventOrganizer + '"')
print('meetingConferencing="' + eventConferencing + '"')
print('meetingInProgress="' + inProgress + '"')
The Raspberry Pi's time is set correctly:
pi#raspberrypi:~ $ date
Fri 16 Jul 20:31:38 BST 2021
The Python script returns this when run:
pi#raspberrypi:~ python /myPythonScript.sh
meetingStart="2021-07-16T20:00:00+01:00"
meetingEnd="2021-07-16T21:00:00+01:00"
meetingTitle="Test"
meetingOrganizer="abc#def.com"
meetingConferencing=" "
meetingInProgress="false"
See a sample code below that will adjust your datetime to UTC regardless of Daylight Saving Time.
Code:
import datetime
import pytz
timeZone = pytz.timezone("Europe/London")
dt = datetime.datetime.utcnow()
print("datetime now is:\t", dt)
local_dt = timeZone.localize(dt, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print("Non-DST time is:\t", utc_dt) # prints utc regardless of DST
Output using bst datetime:
Output using utc datetime:
In your case:
timeZone = pytz.timezone("Europe/London")
dt = datetime.datetime.utcnow()
local_dt = timeZone.localize(dt, is_dst=None)
# timeStamp_now below should be in UTC already
timeStamp_now = local_dt.astimezone(pytz.utc)
Reference:
How to convert local time string to UTC?
Python daylight savings time
I'm looking for a conversion of just am/pm string into time so I could do comparison between 2 different time of the day. I tried using time.strptime or something similar but it seems they all require date as well as time.
My code below:
current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"
import datetime
ct_time = str(datetime.time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(datetime.time(due_hour, due_minute))+due_section
print(due_time)
ct_time_str = time.strptime(ct_time, '%H:%M:%S') # how to format this to time?
due_time_str= time.strptime(due_time,'%H:%M:%S') # how to format this to time?
if (ct_time_str>due_time_str):
print("still have time to turn in assignment")
else:
print("too late")
Getting the below error, not sure how to convert to 'time' from str.
Traceback (most recent call last):
File "main.py", line 15, in <module>
ct_time_str = time.strptime(ct_time, '%H:%M:%S')
NameError: name 'time' is not defined
datetime can be confusing because both the module and class are called datetime.
Change your import to from datetime import datetime, time. Also imports should go at the very top, but it's not strictly necessary.
When assigning ct_time and due_time, you use str(datetime.time(args)), it should just be str(time(args)).
strptime is from datetime, not time, so change time.strptime(args) to datetime.strptime(args)
Also like DeepSpace & martineau said, you need to add '%p' to the format string to account for the AM/PM part.
Final code:
from datetime import datetime, time
current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"
ct_time = str(time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(time(due_hour, due_minute))+due_section
print(due_time)
ct_time_str = datetime.strptime(ct_time, '%H:%M:%S%p')
due_time_str= datetime.strptime(due_time,'%H:%M:%S%p')
if (ct_time_str < due_time_str):
print("still have time to turn in assignment")
else:
print("too late")
edit:
changed if (ct_time_str < due_time_str): to if (ct_time_str > due_time_str):
I'm making a clock that shows me both the time in the UK and in Florida on a continuous loop but when I run the Code it only displays the time I started the run the Code.
Bear in mind that this is my first project. So any amateurish tips will also be helpful
The code itself:
#UK Time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
#Florida time
from datetime import timedelta
minus_hours = now - timedelta(hours=5)
display_minus_hours = minus_hours.strftime("%H:%M:%S")
while True:
print('UK =', current_time)
print('Florida =', display_minus_hours)
you need to update your variables in the loop.
from datetime import datetime, timedelta
while True:
# UK Time
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# Florida time
minus_hours = now - timedelta(hours=5)
display_minus_hours = minus_hours.strftime("%H:%M:%S")
print('UK =', current_time)
print('Florida =', display_minus_hours)
p.s. this prints a lot of stuff out without changing, consider adding a time.sleep(1)
The problem is that the variable is only assigned once.
var = datetime.now()
while True:
print(var)
You need to update the variable every iteration.
while True:
var = datetime.now()
print(var)
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"
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