I'm trying to make a simple clock and I want the format to have the numeric hour without a padding zero. According to every source I can find on google the symbol for that is %l but that gives me a traceback error? It works fine if I use %I though.
def count():
global time1
global date1
time2 = time.strftime('%l:%M %p')
date2 = time.strftime('%A, %B %d %Y')
if time2 != time1:
time1 = time2
clock.config(text=time2)
if date2 != date1:
date1=date2
date.config(text=date2)
clock.after(500, count)
Traceback (most recent call last):
File "D:/Program Files (x86)/pycharm/Projects/test.py", line 48, in count
time2 = time.strftime('%l:%M %p')
ValueError: Invalid format string
Process finished with exit code 1
You want %-I:
time2 = time.strftime('%-I:%M %p')
http://strftime.org/ is a nice reference for Python's strftime format strings.
Related
I get this traceback error below when I run the following code:
from datetime import date
def main():
today = date.day()
print("today is ", today)
if __name__ == "__main__":
main()
error
Traceback (most recent call last):
File "/Users/Documents/CODE X/loops/super_hero_mix.py", line 9, in <module>
main()
File "/Users/Documents/CODE X/loops/super_hero_mix.py", line 4, in main
today = date.day()
TypeError: 'getset_descriptor' object is not callable
Perhaps you wanted to use date.today():
from datetime import date
def main():
today = date.today()
print("today is ", today)
if __name__ == "__main__":
main()
Output:
today is 2021-09-06
Use date.today() to get today's date. If you need the day of the month, use date.today().day.
If you're trying to get today's date, you can do:
from datetime import datetime
def main():
today = datetime.now().date()
print("today is ", today)
if __name__ == "__main__":
main()
If it's the day of the month you're after:
from datetime import datetime
datetime.now().date().day
If it's the day of the week you are after, then use:
from datetime import datetime
now = datetime.now()
print(now.strftime("%A"))
I'm trying to get the difference between two time-stamps: 1606294772889 and 1606295867656. But I keep getting OSError: [Errno 22] Invalid argument
Here is my code:
from datetime import datetime
def get_duration(start , end):
fmt = '%Y-%m-%d %H:%M:%S'
start = datetime.utcfromtimestamp(start).strftime(fmt)
end = datetime.utcfromtimestamp(end).strftime(fmt)
tstamp1 = datetime.strptime(start, fmt)
tstamp2 = datetime.strptime(end, fmt)
if tstamp1 > tstamp2:
td = tstamp1 - tstamp2
else:
td = tstamp2 - tstamp1
td_mins = int(round(td.total_seconds() / 60))
print('The difference is approx. %s minutes' % td_mins)
get_duration(start = 1606294772889 , end = 1606295867656)
Traceback:
Traceback (most recent call last):
File "c:/Users/Yas_!_ru/Documents/GitHub/Mindustry-Ranked/webdriver.py", line 220, in <module>
Match.get_duration(start = 1606294772889 , end = 1606295867656)
File "c:/Users/Yas_!_ru/Documents/GitHub/Mindustry-Ranked/webdriver.py", line 207, in get_duration
start = datetime.utcfromtimestamp(start).strftime(fmt)
OSError: [Errno 22] Invalid argument
The problem here is that your timestamps seems to be in some subdivision of a second. Probably milliseconds.
When I tried your code I had the same error as Tomerikoo in the comments, I divided the timestamps by 1000 it gave me 182 minutes.
Be sure to check in which format the timestamp are given (miliseconds, tenth of a second etc...), in order to convert them back to seconds to use the datetime functions.
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 found a curious bug.
When I used the library wx, my function strptime, which comes of datetime library, doesn't work.
Example :
from datetime import datetime
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
When I execute the previous code and wx.app() I have the following error:
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
Traceback (most recent call last):
File "<ipython-input-108-b41842200da1>", line 1, in <module>
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
File "C:\Simu\WinPython_3741\python-3.7.4.amd64\Lib\_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Simu\WinPython_3741\python-3.7.4.amd64\Lib\_strptime.py", line 359, in _strptime
(data_string, format))
ValueError: time data 'Wed Feb 19 14:57:58 2020' does not match format '%a %b %d %H:%M:%S %Y'
What is the link between the datetime and wx ?
And how to fix this bug ?
Resolved !
This bug comes from localtime. I don't know why but when I execute wx.app(), my localtime change.
I discovered this thanks to the following command :
from time import strftime,localtime
print(strftime("%H:%M, %d %B %Y",localtime()))
10:44, 20 février 2020
To change the localtime, here is the code :
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
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)