I used the %-I format for time, but it throws an error saying
"Traceback (most recent call last):
File "c:\Users\Lenovo\Desktop\VA Project\EDITH.py", line 31, in
timeEve = now.strftime("%-I %M")
ValueError: Invalid format string"
import pyttsx3
import tkinter
import speech_recognition as sr
import datetime
import time
from datetime import date
today = date.today()
now = datetime.datetime.now()
# Textual month, day and year
d8 = today.strftime("%A %B %d, %Y")
time = now.strftime("%H%M")
timeDay = now.strftime("%M")
timeEve = now.strftime("%-I %M") #THIS IS WHERE THE PROBLEM IS WITH THE "%-I"
def askTime():
engine = pyttsx3.init()
engine.setProperty('rate', 170) # Decrease the Speed Rate x2
if int(time)<1200:
engine.say("Good morning!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeDay)
engine.runAndWait()
if int(time)>1200 and int(time)<1600:
engine.say("Good afternoon!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeEve)
engine.runAndWait()
if int(time)>1600:
engine.say("Good evening!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeEve)
engine.runAndWait()
Related
Hi I have 2 functions these functions have a different types of import of datetime. I know where is problem but I do not know how to solute it
my code:
from datetime import datetime
import datetime
def upload_video(title,description,tags,upload_year,uplaod_month,upload_day):
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z'
print(f"this is a upload time {upload_date_time}")
request_body = {
'snippet': {
'categoryI': 19,
'title': title,
'description': description,
'tags': tags
},
'status': {
'privacyStatus': 'private',
'publishAt': upload_date_time,
'selfDeclaredMadeForKids': False,
},
'notifySubscribers': False
}
mediaFile = MediaFileUpload('output.MP4')
response_upload = service.videos().insert(
part='snippet,status',
body=request_body,
media_body=mediaFile
).execute()
def date_calculator():
days_in_months = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
year = datetime.now().year
month = datetime.now().month
# Read the last used date from the text file
with open("last_used_date.txt", "r") as f:
last_used_date = f.read().strip()
# If the file is empty or the date is invalid, set the last used date to the current date
if not last_used_date or not all(c.isdigit() for c in last_used_date.split(".")):
last_used_day = datetime.now().day
last_used_month = month
else:
last_used_day, last_used_month = map(int, last_used_date.split(".")[:2])
# Generate new dates until the next one is greater than the current date
number = 0
number_test = 1
while True:
date = "{}.{}.{}".format(last_used_day, last_used_month, year)
number += 1
if last_used_day == days_in_months[month]:
last_used_month += 1
last_used_day = 1
else:
last_used_day += 1
if number == 2:
last_used_day += 1
number = 0
number_test += 1
if (last_used_month > month or
(last_used_month == month and last_used_day > datetime.now().day)):
with open("last_used_date.txt", "w") as f:
f.write("{}.{}.{}".format(last_used_day, last_used_month, year))
break
return last_used_day,last_used_month,year
error:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 233, in
day,month,year = date_calculator() File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 162, in date_calculator
year = datetime.now().year AttributeError: module 'datetime' has no attribute 'now'
if I will change imports like this:
import datetime
from datetime import datetime
error will look like that:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 235, in
upload_video(title,"#Shorts", ["motivation", "business", "luxury", "entrepreneurship", "success", "lifestyle", "inspiration", "wealth",
"financial freedom", "investing", "mindset", "personal development",
"self-improvement", "goals", "hustle", "ambition", "rich life",
"luxury lifestyle", "luxury brand", "luxury travel", "luxury
cars"],year,month,day) File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 74, in upload_video
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00,
0).isoformat() + '.000Z' AttributeError: type object
'datetime.datetime' has no attribute 'datetime'
Unfortunately, the datetime module and the datetime class inside it are spelled exactly the same way. You need to pick one of those things to import and then use it consistently. i.e. either:
import datetime # I want the whole datetime module
datetime.datetime.now() # Must use the fully qualified class name
datetime.date.today() # But I can also use other classes from the module
Or:
from datetime import datetime # I only want the datetime class
datetime.now() # Use the class directly
The name datetime can only mean one thing at a time, so if you do both imports, all that's happening is that the second meaning overwrites the first one.
from tkinter import *
from tkinter.ttk import *
from time import strftime
root = Tk()
root.title('Clock')
def time():
string = strftime('%H:%M:%S %P')
label.config(text=string)
label.after(1000, time)
label = Label(root, font=("ds-digital", 80), background="black", foreground="cyan")
label.pack(anchor='center')
time()
mainloop()
I got this error
File "c:\Users\david\OneDrive\Desktop\practice projects\clock.py", line 16, in <module>
time()
File "c:\Users\david\OneDrive\Desktop\practice projects\clock.py", line 10, in time
string = strftime('%H:%M:%S %P')
ValueError: Invalid format string
Try lower case P:
string = strftime('%H:%M:%S %p')
but this is 24 hour base so you might not need AM or PM. If you want 12 Hour based, use:
string = strftime('%I:%M:%S %p')
Docs:
https://www.programiz.com/python-programming/datetime/strftime
I had this same error while following a youtube tutorial for it as a beginner and for me the fix was simple making the P in my string lowercase. ('%H:%M:%S %p')
I received the datetime in below format
timestamp = '2019-03-18 01:50:00 -0800'
and wanted to convert into datetime in python
i tried but won't able to pick the UTC offset
from datetime import datetime
from datetime import timedelta
timestamp = '2019-03-18 01:50:00 -0800'
date_format = '%Y-%m-%d %H:%M:%S %z'
d_t =datetime.strptime(timestamp,date_format)
Error i get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
how to pick UTC offset in python 2.7?
Just use dateutil
from dateutil import parser
obj = parser.parse('2019-03-18 01:50:00 -0800')
print(obj)
#2019-03-18 01:50:00-08:00
Install pytz library
sudo easy_install --upgrade pytz
Import pytz to code
from datetime import datetime
from pytz import timezone
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") #parse only date & time
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC')) #get time zone using pytz
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")
It should help.
Can someone help with me this?
I am using Flatlib to compute planet positions, but the code for entering the date and time for computation is fixed, so you have to update it each time.
Is there a way to using datetime.now() [or another way] to complete the fields in the Datetime() automatically? I can't get the code in the date = Datetime() to accept any form of datetime code.
I looking to get Datetime() to accept month/day/year and hour:minute:second format eg (08/24/2018, 21:17:00)
With the below code i get the following error:
C:\Users\famil>C:\Users\famil\Desktop\flatlib_working_degree.py
('{0.month}/{0.day}/{0.year}', '21:15:41')
Traceback (most recent call last):
File "C:\Users\famil\Desktop\flatlib_working_degree.py", line 13, in
date = Datetime(x)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 177, in init
self.date = Date(date, calendar)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 76, in init
self.jdn = int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const
import datetime
# set date and time to now
now = datetime.datetime.now()
x = '{0.month}/{0.day}/{0.year}, {0.hour}:{0.minute}:{0.second}'.format(now)
print(x)
date = Datetime(x)
pos = GeoPos('53n15', '2e31')
chart = Chart(date, pos, hsys=const.HOUSES_PLACIDUS, IDs=const.LIST_OBJECTS)
# calculate body and degree value
asc = chart.get(const.ASC)
print(asc, asc.lon)
sun = chart.get(const.SUN)
print(sun, sun.lon, sun.movement())
moon = chart.get(const.MOON)
Flatlib's Datetime demands 2 separate inputs for date and time, as you can check here: Github: flatlib/datetime.py
.
def __init__(self, date, time=0, utcoffset=0, calendar=GREGORIAN):
But your code has only datetime 1 argument, separated by comma. That's incorrect:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d, %H:%M"))
You should write it like this:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d"), now.strftime('%H:%M'))
I have a python script
import urllib2
from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(date,month,year):
today = date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
But i get this error-
Traceback (most recent call last):
File "test.py", line 17, in <module>
print generateDateList(4,12,2017)
File "test.py", line 11, in generateDateList
today = date(year, month, date)
TypeError: 'int' object is not callable
Why is it failing? I substituted the function with values and it worked. Should i convert the function inputs to integer again?
This line - def generateDateList(date,month,year):
The name of the first argument date shadows the name date imported at the top. You need to rename the argument to something like day inside your function.
As written, date is actually an integer you pass to the function, and calling it results in an error you are seeing.
Two options.
Option No.1 (import datetime):
import datetime
def generateDateList(date, month, year):
today = datetime.date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.datetime.strftime(today + datetime.timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4, 12, 2017)
Option No.2 (rename date parameter to day):
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(day,month,year):
today = date(year, month, day)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
The problem is the fact you have a parameter with the same name of the date() function.