i have problem with this script.
named_tuple = time.localtime()
time_string = time.strftime("%H:%M", named_tuple)
if time_string > "7:00" or time_string < "18:00":
print("day")
else:
print("evening")
how can I check day or evening please?
You can retrieve the hour from what time.localtime() returns:
>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=12, tm_hour=19, tm_min=..., tm_sec=..., tm_wday=2, tm_yday=163, tm_isdst=...)
>>> _.tm_hour
19
Then you just compare tm_hour with the values you want:
Time = time.localtime()
if 7 <= Time.tm_hour <= 18:
print('Yeah!')
If you need to be more precise, grab the minutes:
if (6, 45) <= (Time.tm_hour, Time.tm_min) <= (18, 5):
...
You cannot use your time_string to check if it's greater than "7:00" or smaller than "18:00", because it ranks strings according to alphanumerical order.
For example, it's now 12:32. The first character of my time_string would be "1", which is smaller than "7", so it would print "evening" even if it's noon.
Also, you want to check if it's later than 7:00 AND earlier than 18:00.
Maybe you can add more options too, because any time earlier than 7:00 would print "evening".
As for how to do it, see ForceBru's answer, which keeps it super simple.
Right now the first statement will always match.
Your time will ALWAYS be greater than 7:00 OR less than 18:00.
Change or to and and it should work.
EDIT:
I had just glanced at the if statement briefly and noticed that it was broken. Fundamentally having the or in there will prevent the else statement from ever being executed. However, looking at it again, there are more errors going on than just the or issue.
Like #ForceBru mentions, you'll want to get the hour so that you're not doing a string comparison.
Related
import datetime
now = datetime.datetime.now()
if now.day == Tuesday :
print ('yes it is tuesday')
else :
print ('no')
I try this but I get error in python :
Traceback (most recent call last):
File "C:/Users/Yarlagadda/Desktop/test2.py", line 4, in <module>
if now.day == Tuesday :
NameError: name 'Tuesday' is not defined
>>>
I would like to know mistake
You have two problems with your code.
The first is that the error code is telling you that Tuesday doesn't exist as a variable because you are not making it a string. So change it to 'Tuesday' with the ' around it.
Second is that now.day is going to return a number and not a string day.
Edit: Thanks to #Tomerikoo for pointing out that this returns the day of the month and not the day of the week. Change this to now.weekday() to get the day of the week.
To fix this, you can either compare the number 1 in the if statement instead of the word Tuesday or you can map the numbers to the words. Mapping the numbers to the words is the preferred method since it is easier to maintain and less messy.
Note: The days of the week in now.weekday() will be numbered 0-6 with 0 being Monday and 6 being Sunday.
I'm using a tuple here, but you could use a list, or if you really feel inclined, a dictionary. But a dict is overkill and a list comes with memory overhead that's not needed.
Mapping:
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
Final Code
import datetime
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
now = datetime.datetime.now()
day = week_days[now.weekday()] # Note the change to now.weekday()
if day == 'Tuesday' :
print ('yes it is tuesday')
else :
print ('no')
The error is just in if condition that the Tuesday is not used as string. Replace Tuesday by 'Tuesday' and your code is working fine.
For enhancement you may also use list or tuple to keep the weekdays.
import datetime
now = datetime.datetime.now()
if now.day == 'Tuesday':
print ('yes it is tuesday')
else:
print ('no')
I started to write
import time
localtime = time.localtime()
print(localtime)
but the localtime gives nine attributes
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=31, tm_hour=22,
tm_min=32, tm_sec=41, tm_wday=1, tm_yday=212, tm_isdst=1)
I want to find whether its am or pm in python by comparing hours:min:sec with the local time. Please suggest
tm_hour=22
This is the field you're interested in(a), and you can get at the individual fields just by using (e.g., for the hour) localtime.tm_hour.
You can then use it to figure out what part of the day it is, as follows:
0 - 11 -> am, 12 - 23 -> pm
A simple bit of code for this would be:
import time
mytime = time.localtime()
if mytime.tm_hour < 12:
print ('It is AM')
else:
print ('It is PM')
For something more airy-fairy (like day and night), the simplest solution would be fixed times like:
0 - 5, 19 - 23 -> night, 6 - 18 -> day
done with:
import time
mytime = time.localtime()
if mytime.tm_hour < 6 or mytime.tm_hour > 18:
print ('It is night-time')
else:
print ('It is day-time')
That, of course, depends entirely on how you define day and night since the sun rises and sets at different times in different parts of the world at different times of the year and, in extreme cases of far-north and far-south latitudes, sometimes not for months at a time.
(a) Technically you probably should be using hour, minute and possibly even second, since it can be argued that both midday and midnight are neither ante-meridian nor post-meridian. But we'll go with simpler solutions in the context of this question.
Sample code, ignoring seconds, follows:
import time
mytime = time.localtime()
myhour = mytime.tm_hour
mymin = mytime.tm_min
if myhour == 0 and mymin == 0:
print('It is midnight')
elif myhour < 12:
print ('It is AM')
elif myhour == 12 and mymin == 0:
print('It is noon')
else:
print ('It is PM')
I have a path files which are named by time (201803061500) etc. What I need is a time conversion, because I use while loop to open a few of them there is an error when I want files from for example (...1555 to ... 1615) and Python sees an obivous problem because after 1555 is 1560, but I want him to convert that to time so after (...1555 will be ... 1600) any ideas how to use it?
Btw. Time conversion must be contain 4 digits, so it cannot be 16:00/16-00 etc. it must be 1600, because it goes as an input to my pathfile. Any ideas?
UPDATE - I did this, but this code is rubbish and I think my problem might be solved by one command.
Start_time_hours = input('Enter start time (hh): ' )
Start_time_minutes = input('Enter start time (mm): ')
if Start_time_hours >= 24:
print ("Values from 00 to 23 only!")
if Start_time_minutes >= 60:
x = Start_time_hours + 1
y = Start_time_minutes - Start_time_minutes
if y == 0:
print "Ok"
print x, y
if Start_time_minutes <= 55:
print Start_time_hours, Start_time_minutes
One easy way to handle unformated time is the datetime. You can first strip your strings and then do whatever you want !
from datetime import datetime, timedelta
from time import strtime
datetime_object = datetime.strptime(file_name, '%Y%m%d%H%M')
print(datetime_object) # returns '2018-03-06 15:00:00'
delta = timedelta(minutes=5)
next_time = datetime_object + delta
print(next_time) # returns '2018-03-06 15:05:00'
Finally you can get your string back by using time.strftime() function
new_string = next_time.strftime('%Y%m%d%H%M')
print(new_string) # returns '201803061505'
Source datetime: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
Source time: https://docs.python.org/2/library/time.html
Start_time_hours += (Start_time_minutes / 60)
Start_time_minutes %= 60
Start_time_minutes += 5
Those three lines solved my problem, datetime also works, but if you put those variables to input pathfile, you'll get an error. That's why I've choosen this solution.
I need to make a simple program which converts a 24 hour time which is input, into 12 hour time, which produces an error if an incorrect time is put in. I currently have the code below, however, I have a few issues. One issue is that if "0924" is input, it outputs "924 am", when I need it to produce "9:24am" (the space isn't hugely important but it's preferred). Also, I'm not entirely sure where to start for doing 0001-0059, because "0001" for example produces "1 am", which is obviously incorrect.
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = (time - 1200)
print (int(normal), ("pm"))
elif (time<1200):
normal = time
print (int(normal), ("am"))
Thanks in advance for any help!
Try this
import time
timevalue_24hour = "1620";
timevalue_24hour = timevalue_24hour[:2] + ':' + timevalue_24hour[2:]
print (timevalue_24hour)
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )
print (timevalue_12hour)
Take input as a string. Assign it to timevalue_24hour and rest will work
When printing, normal is just a number. The 0s disappear because you don't write 0s in front of numbers normally. I would suggest doing something like this
def normal_check(num):
if num < 10:
return "000"+str(num)
elif num < 100:
return "00"+str(num)
elif num < 1000:
return "0"+str(num)
else:
return str(num)
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = normal_check(time - 1200)
print (normal, ("pm"))
elif (time<1200):
normal = normal_check(time)
print (normal, ("am"))
The best way to do this will be to take the input as an str rather than int. Take it in as str and split it into two int values of two digits.
Then the first string if less than 12 will be hour else subtract 12 from first str and use PM. Also, the second str will just be minutes.
I need some help with my code. I have a trouble with changing the strings.
I am checking with the strings if the variable getTime3 have a string 30 then I want to replace it with 00. On my code, it will find the string 30 to replace it with 0030 which is wrong. It should be 00.
Here is the code:
if getTime3 == '11:30PM':
self.getControl(346).setLabel('12:00AM')
elif getTime3 == '12:30PM':
self.getControl(346).setLabel('1:00AM')
else:
ind = getTime3.find(':')
if getTime3[ind+1:ind+3]=='30':
getTime3 = getTime3[:ind]+':00'+getTime3[+2:]
self.getControl(346).setLabel(getTime3)
else:
getTime3 = str(int(getTime3[:ind])+1)+':30'+getTime3[+2:]
self.getControl(346).setLabel(getTime3)
What I am expect for the two special cases, when the program finds the :, it will check if 30 is present then change the current hour to the next hour and make a new string with AM/PM label, example: change from 8 to 9 and replace 30 with 00 to make it to show 9:00PM. If the ending is 00 then I want to change 00 to 30 instead. I want to add 30 in the minute section and again preserves the AM/PM part. If the getTime3 have the string 11:30AM then I want to change it to 12:00PM.
Can you please help me with how to fix the 0030 to make it to show 00 instead and add the next hour?
With Python, slice like x[a:b] in the slice starting at a (inclusive), and finishing at b (exclusive).
So: getTime3[:ind] is the slice from 0 to ind exclusive, which is the hours without the ":".
And indexes are absolute index, not relative. So getTime3[+2:] is the same as getTime3[2:], which correspond to the substring starting at index 2.
What you want is:
getTime3 = getTime3[:ind] + ':00' + getTime3[ind + 3:]
# or
getTime3 = getTime3[:ind + 1] + '00' + getTime3[ind + 3:]
Example:
getTime3 = '08:30PM'
ind = getTime3.index(":")
getTime3[:ind] + ':00' + getTime3[ind + 3:]
# -> '08:00PM'
EDIT
If you want to do some calculation on time, you can use the datetime module.
time_fmt = '%I:%M%p'
Is the format used to represent time like '09:30PM', where:
%I Hour (12-hour clock) as a zero-padded decimal number.
%M Minute as a zero-padded decimal number.
%p Locale’s equivalent of either AM or PM.
How to add 30 min:
import datetime
time3 = '09:30PM'
dt3 = datetime.datetime.strptime(time3, time_fmt)
dt3 += datetime.timedelta(minutes=30)
time3 = dt3.strftime(time_fmt)
If you want to set the minutes to 0, you can do:
dt3 = datetime.datetime.strptime(time3, time_fmt)
dt3 = d3.replace(minute=0)
Please don't use the wrong tool for the task. You are manipulating times, yet using strings to do it. Start with this to turn 11:30PM into 12:00AM:
import datetime
t3 = datetime.datetime.strptime(getTime3, '%I:%M%p')
t3 += datetime.timedelta(minutes=30)
print(t3.strftime('%I:%M%p'))
Adding timedelta(minutes=30) makes the intent perfectly clear. Some relevant documentation is at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior