I am trying to make an alarm clock. How to make a datetime object from user-input, where the user-input is hours, minutes, and secs seperately. For example:
from datetime import datetime
# user-input: at 2:30
hr = "2"
m = "30"
s = "0"
from datetime import datetime
def GetDate():
isValid=False
while not isValid:
userIn = input("Type Date dd/mm/yy: ")
try: # strptime throws an exception if the input doesn't match the pattern
d = datetime.datetime.strptime(userIn, "%d/%m/%y")
isValid=True
except:
print("Invalid")
return d
#test the function
print(GetDate())
Related
rom pathlib import Path
path = Path('/home/hell/Downloads/hello by Adele/')
search_string = 'completed on "%d/%m/%Y"' #%d/%m/%Y today's date
t=0
for o in path.rglob('*.sql'):
if o.is_file():
t= t+1
text = o.read_text()
if search_string not in text:
print(o)
break
search_string = 'completed on "%d/%m/%Y"'
the script is to search for a string.."completed on 13/13/2022". I would like to add date to the current date to the search parameter but cant figure out how.
kindly assist and thanks
first get your today's date to string
from datetime import datetime
dateText = datetime.now().strftime("%d/%m/%Y")
then concat your "search_string"
search_string ='completed on '+dateText
>>> from datetime import datetime
>>> dateText = datetime.now().strftime("%d/%m/%Y")
>>> search_string ='completed on '+dateText
>>> print(search_string)
completed on 26/09/2022
If you use the datetime library, you can get 'today' with
from datetime import date
t = date.today()
This will be a datetime.date object. You can then display it in whatever format you want with the .strftime() method, so you'd have display_date = t.strftime('%d/%m/%Y'). Your new object display_date will be a string in that format.
Do all of that first in your script, and then have your search_string = f'completed on {display_date}'
So in total you will have
from pathlib import Path
from datetime import date
t = date.today()
display_date = t.strftime('%d/%m/%Y')
path = Path('/home/hell/Downloads/hello by Adele/')
search_string = f'completed on {display_date}'
t=0
for o in path.rglob('*.sql'):
if o.is_file():
t= t+1
text = o.read_text()
if search_string not in text:
print(o)
break
I have a python code that looks like this. I am receiving the values
of year, month and day in form of a string. I will test whether they are not null.
If they are not null I will like to generate a date in this format MMddyyyy from the variables
from datetime import datetime
year = "2022"
month = "7"
day = "15"
if len(year) and len(month) and len(day):
print('variables are not empty')
#prepare = "{month}/{day}/{year}"
#valueDt = datetime.strptime(prepare,"%m/%d/%Y")
else:
print('variables are empty')
The solution I have is not working. How can I generate this date?
It should work without calling len as well.
from datetime import datetime, date
year = "2022"
month = "7"
day = "15"
if year and month and day:
print('variables are not empty')
prepare = date(int(year), int(month), int(day))
valueDt = datetime.strftime(prepare, "%m/%d/%Y")
print(valueDt)
else:
print('variables are empty')
from datetime import datetime, date
year = "2022"
month = "7"
day = "15"
if len(year) and len(month) and len(day):
print('variables are not empty')
prepare = date(int(year), int(month), int(day))
valueDt = datetime.strftime(prepare, "%m/%d/%Y")
print(valueDt)
else:
print('variables are empty')
I want my datetime format to be like this "20210613172123" from this "2021-06-13 17:21:23.039823". Is this possible in python?
import datetime
now = datetime.datetime.now()
print(now)
So this is what you need to do :
from datetime import datetime
now = datetime.now()
formatted_time_expression = f'{now.year}{now.month}{now.day}{now.hour}{now.minute}{now.second}{now.microsecond}'
print(formatted_time_expression)
Use strftime to convert datetime object to the required string format.
from datetime import datetime
now = datetime.now()
print(now)
print(now.strftime("%Y%m%d%H%M%S"))
datetime to timestamp
from datetime import datetime
# current date and time
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)
timestamp to datetime
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
from datetime import datetime, timedelta
hours = input("Number of hours:")
time = datetime.now() + timedelta(hours=hours)
print(time)
_________________________________________________________________
Traceback (most recent call last):
File "C:/Users/uruma/Desktop/test.py", line 4, in <module>
time = datetime.now() + timedelta(hours=hour)
TypeError: unsupported type for timedelta hours component: str
from datetime import datetime, timedelta
hours = 4
time = datetime.now() + timedelta(hours=hours)
print(time)
____________________________
2020-10-28 06:00:30.149767
What I'm trying to do here is ask the user for the number of hours in order to calculate what hour will be after a certain amount of time, but I get an error. But if instead of the "input" code you put a number ... How to solve?
By default, the value from input() is string.
Convert the input string into int
from datetime import datetime, timedelta
hours = int(input("Number of hours:"))
time = datetime.now() + timedelta(hours=hours)
print(time)
You need to convert the user input to an integer before using it. Python input is a string by default.
hours = int(input('Enter the number of hours: '))
I'm able to convert ISO-date format to simple date format as below.
from dateutil.parser import parse
date_string = '2018-03-12T10:12:45Z'
dt = parse(date_string)
print(dt.date()) #prints 2018-03-12
print(dt.time()) #prints 10:12:45
print(dt.tzinfo) #prints tzutc()
How to convert it other way ? examples shown below
If input is `2018-03-12` , then output should be `2018-03-12T00:00:00Z`
If input is `2018-03-12-10-12-45` , then output should be `2018-03-12T10:12:45Z`
I am accepting two inputs (format : yyyy-mm-dd) and trying to form date-range between from-date and to-date in iso-format. How can I do that (as below) ?
input1 : `2018-03-12` , output1 : `2018-03-12T00:00:000Z` (12AM, 24-hr format)
input2 : `2018-03-15` , output2 : `2018-03-15T23:59:000Z` (11:59PM, 24-hr format)
Solution:
import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)
Output:
2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z
you can use datetime module (if there is only 2 expected patterns, you can simply do try-except)
str_date = '2018-03-12'
def convert(x):
try:
return datetime.strptime(x, '%Y-%m-%d-%H-%M-%S')
except ValueError:
return datetime.strptime(x, '%Y-%m-%d')
convert(str_date)
Solution:
import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)
Output:
2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z