Convert string "AM" or "PM" then add to time without date - python

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):

Related

Python/Pywinauto CurrentTime==Given Time until Statement is True but it's always false

Expected Behavior
Check if CurrentTime == GivenTime(via input)
if Statement is True click Button
Actual Behavior
Checks if CurrentTime is GivenTime but if I check the bool even tho for example Current and GivenTime are both 13:29:50
bool is still False and the loop just continues.
from pywinauto import Application
import time
from pywinauto.timings import Timings
from datetime import datetime
from _strptime import _strptime
app = Application(backend="uia").connect(title_re=u'Website', timeout=100)
Timings.after_clickinput_wait = 0
STime = input('insert STime:')
STime2 = datetime.strptime(STime,'%H:%M:%S')
print(type(STime2))
CurrentTime= datetime.now()
while STime2 != CurrentTime:
CurrentTime = datetime.now()
print("%s:%s:%s" % (CurrentTime.hour,CurrentTime.minute,CurrenTime.second))
time.sleep(1)
else:
app.Website.child_window(title='Button' , control_type="Button").click_input()
this is one variant i have tried but it doesent recognize the else because it cant break the while loop because the statement STime2 != CurrentTime is always True so the Current Time is never the STime2 even if it should.
The second variant is:
from pywinauto import Application
import time
from pywinauto.timings import Timings
from datetime import datetime
from _strptime import _strptime
app = Application(backend="uia").connect(title_re=u'Website', timeout=100)
Timings.after_clickinput_wait = 0
STime = input('insert STime:')
STime2 = datetime.strptime(STime,'%H:%M:%S')
flag = True
while flag is True:
CurrentTime=datetime.now()
print("%s:%s:%s" % (CurrentTime.hour,CurrentTime.minute,CurrenTime.second))
time.sleep(1)
Time = CurrentTime == STime2
if Time is True:
flag = False
app.Website.child_window(title='Button' , control_type="Button").click_input()
I dont get an Error but what it does is, it outputs me the currentTime so i can see the Time where the Time i typed in and the CurrentTime should be the same but it does nothing and just ignores the if or else code of the variants.
i already got suggested that input is String and the CurrentTime is datetime.datetime but now I changed the input to datetime.datetime and it still doesent work.. anybody got an idea how to make it work?
i have also tried it with if (CurrentTime == STime2): still doesn't work
You're working with datetime objects, but only providing the time of day in one of them. Python is providing a default date for the rest.
from datetime import datetime
STime = input('insert STime:')
STime2 = datetime.strptime(STime,'%H:%M:%S')
CurrentTime= datetime.now()
print(STime2)
print(CurrentTime)
Output:
insert STime:9:26:00
1900-01-01 09:26:00
2022-08-22 09:25:22.675953
The current time is never going to be equal to 1900-01-01 09:26:00. You need to either get just the time of day from each datetime object, or have the user input both the date and time.
Either way, check the values you are comparing (either in your debugger or using print statements like I did here) to make sure they could reasonably be expected to be equal.

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

Making the subtraction posssible: 'datetime.time' and 'datetime.datetime'

I'm Salech and I'm learning Python. Python is my really first programming language. It is my second day that I following the youtube video "from zero to hero". And my first problem that I can't solve is related to time and date.
The challenge:
Ask a user to enter a deadline for their project
Tell them how many days they have to complete the project
For Extra Credit give them the answer as a combination of weeks & days
I made all of that, but then I thought to add an additional feature, which takes an input of time(hh:mm:ss) and prints this time minus the current time. Here's how I thought to do it:
import math
import datetime
currentDate = datetime.date.today()
currentTime = datetime.datetime.now()
deadLine = input('Hello, enter the deadline date for your project (mm/dd/yyyy)')
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
deadLineTime = input('insert time')
deadTime = datetime.datetime.strptime(deadLineTime, '%H:%M:%S').time()
print(deadTime)
daysLeft = deadLineDate - currentDate
print('%d days left' % daysLeft.days)
weeksLeft = math.floor(daysLeft.days/7)
newDaysLeft = daysLeft .days- 7*(math.floor(daysLeft.days/7))
print('You have %d weeks' % weeksLeft, ' and %d days left.' % newDaysLeft)
timeLeft = deadTime - currentTime
print(timeLeft.hours)
With the input 02/04/2016 and 15:00 I get the following error:
Hello, enter the deadline date for your project (mm/dd/yyyy)02/04/2016
insert time15:00
15:00:00
5 days left
You have 0 weeks and 5 days left.
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 31, in <module>
timeLeft = deadTime - currentTime
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.datetime'
>>>
Edit: As jonatan said, testing the code without any input:
Hello, enter the deadline date for your project (mm/dd/yyyy)
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 14, in <module>
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 507, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 344, in _strptime
(data_string, format))
ValueError: time data '' does not match format '%m/%d/%Y'
Thank You.
You need to combine your date and your time into a datetime.
deadline = datetime.datetime.combine(deadLineDate, deadlineTime)
timeLeft = deadline - currentTime
The reason for the error is because it doesn't really make much sense to subtract a date from a time. e.g. What is "4PM - Fri, Jan 29th?".
import datetime
import math
currentDate=datetime.date.today()
currentTime=datetime.datetime.now()
UserInput1=input("What is the deadline for your project? mm/dd/yyyy ")
deadLine=datetime.datetime.strptime(UserInput1, "%m/%d/%Y").date()
UserInput2=input("Please insert the time hh/mm/ss ")
deadTime=datetime.datetime.strptime(UserInput2, "%H/%M/%S").time()
daysLeft= deadLine-currentDate
print("%d days left" % daysLeft.days)
weeksLeft=math.floor(daysLeft.days/7)
newDaysLeft=daysLeft.days-7*(math.floor(daysLeft.days/7))
print("You have %d weeks" % weeksLeft, "and %d days left."% newDaysLeft)
deadLine=datetime.datetime.combine(deadLine,deadTime)
timeLeft=deadLine-currentTime
print(timeLeft)

'str' object is not callable TypeError

In my code I am trying to extract some data from a file. I am getting this error when I am trying to run my code on line 61. My code here:
from datetime import date
from math import floor;
from adjset_builder import adjset_builder
def check_and_update(d,start,end,log):
# print start,end;
if start in d:
if end in d[start]:
log.write("{0}-{1}\n".format(start, end))
if d[start][end] == 1:
print "one found"
d[start][end] += 1
def build_dictionary(my_adjset,my_list,factor,outfile,log):
log.write("building dictionary:\n");
window_size = int(floor(len(my_list)*factor));
if window_size<2:
log.write("too small\n")
return;
log.write('Total:{0},windowsize:{1}\n'.format(len(my_list),window_size));
log.write("Window at place: 0,")
for i in xrange(window_size):
j = i+1;
while j<window_size:
check_and_update(my_adjset, my_list[i][1], my_list[j][1],log);
j=j+1
i=1;
while i<=len(my_list)-window_size:
log.write("{0},".format(i))
j=i;
k=i+window_size-1;
while j<k:
check_and_update(my_adjset, my_list[i][1], my_list[j][1],log);
j+=1
i += 1
log.write("\nDictionary building done\n")
def make_movie_list(infilename,factor):
log=open('log.txt','w');
outfile=open(infilename.split('.')[0]+"_plot_"+str(factor)+".txt",'w');
f=open(infilename,'r');
my_adjset=dict()
adjset_builder('friends.txt', my_adjset);
count =1
while True:
string = f.readline();
if string=='':
break;
log.write("count:{0}\n".format(count))
count += 1
[movie,freunde] = string.split('=');
freunde = freunde.split(';')
mylist=[]
for i in freunde:
[user_id,date] = i.split(' ');
[yy,mm,dd] = date.split('-');
# l=list((date(int(yy),int(mm),int(dd)),user_id))
mylist.append([date(int(yy),int(mm),int(dd)),user_id]); ## line 61
log.write("list built");
print mylist
break;
# build_dictionary(my_adjset, mylist, factor,outfile,log)
del(mylist);
print 'Done'
log.close();
outfile.close();
f.close();
print count
if __name__ == '__main__':
make_movie_list('grades_processed.txt',.5)
However when I tried to simulate the same thing in 'Console' I do not get any error:
dd='12'
mm='2'
yy='1991'
user_id='98807'
from datetime import date
from datetime import date
l=list((date(int(yy),int(mm),int(dd)),user_id))
l [datetime.date(1991, 2, 12), '98807']
Might be something very silly but I am a beginner so can not seem to notice the mistake. Thank you!
This makes date a function:
from datetime import date
This makes date a string:
[user_id,date] = i.split(' ');
You get a TypeError now, since date is no longer a function:
mylist.append([date(int(yy),int(mm),int(dd)),user_id]);
One way to avoid this error is to import modules instead of functions:
import datetime as dt
mylist.append([dt.date(int(yy),int(mm),int(dd)),user_id])
or more succinctly,
mylist.append([dt.date(*date.split('-')), user_id])
PS: Remove all those unnecessary semicolons!
You have a variable called date, rename it so that it doesn't shadow the date function from datetime.

Print file age in seconds using Python

I need my script to download a new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds.
This shows how to find a file's (or directory's) last modification time:
Here are the number of seconds since the Epoch, using os.stat
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52
Or, equivalently, using os.path.getmtime:
print(os.path.getmtime('/tmp'))
# 1325704746.52
If you want a datetime.datetime object:
import datetime
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398
Or a formated string using time.ctime
import stat
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
# last accessed => Wed Jan 4 14:09:55 2012
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
# last modified => Wed Jan 4 14:19:06 2012
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
# last changed => Wed Jan 4 14:19:06 2012
Although I didn't show it, there are equivalents for finding the access time and change time for all these methods. Just follow the links and search for "atime" or "ctime".
Another approach (I know I wasn't the first answer but here goes anyway):
import time, os, stat
def file_age_in_seconds(pathname):
return time.time() - os.stat(pathname)[stat.ST_MTIME]
The accepted answer does not actually answer the question, it just gives the answer for last modification time. For getting the file age in seconds, minutes or hour you can do this.
import os, time
def file_age(filepath):
return time.time() - os.path.getmtime(filepath)
seconds = file_age('myFile.txt') # 7200 seconds
minutes = int(seconds) / 60 # 120 minutes
hours = minutes / 60 # 2 hours
Use stat.M_TIME to get the last modified time and subtract it from the current time.
http://docs.python.org/library/stat.html
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, time
def file_age_in_seconds(filename):
try:
return int(time.time() - os.path.getmtime(filename))
except:
#on any failure condition
return -1
filename = "/tmp/foobar.txt"
print(file_age_in_seconds(filename)) #prints -1
f = open(filename, 'w')
f.write("this is a line")
f.close()
print(file_age_in_seconds(filename)) #prints 0
time.sleep(4.2)
print(file_age_in_seconds(filename)) #prints 4
This will do in days, can be modified for seconds also:
#!/usr/bin/python
import os
import datetime
from datetime import date
t1 = os.path.getctime("<filename>")
now = datetime.datetime.now()
Y1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%Y'))
M1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%m'))
D1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%d'))
date1 = date(Y1, M1, D1)
Y2 = int(now.strftime('%Y'))
M2 = int(now.strftime('%m'))
D2 = int(now.strftime('%d'))
date2 = date(Y2, M2, D2)
diff = date2 - date1
days = diff.days
You can get it by using OS and datetime lib in python:
import os
from datetime import datetime
def fileAgeInSeconds(directory, filename):
file = os.path.join(directory, filename)
if os.path.isfile(file):
stat = os.stat(file)
try:
creation_time = datetime.fromtimestamp(stat.st_birthtime)
except AttributeError:
creation_time = datetime.fromtimestamp(stat.st_mtime)
curret_time = datetime.now()
duration = curret_time - creation_time
duration_in_s = duration.total_seconds()
return duration_in_s
else:
print('%s File not found' % file)
return 100000
#Calling the function
dir=/tmp/
fileAgeInSeconds(dir,'test.txt')

Categories