Add a year to current date - python

from datetime import *
date = date.today()
Printing date gives me "2020-07-21"
How may I go about adding a year to that date?

from datetime import *
from dateutil.relativedelta import relativedelta
date = date.today()
newDate = date + relativedelta(years=1)

Try:
import datetime as dt
d = date.today()
dt.date(d.year + 1,d.month, d.day)

Related

Time to next full hour

I have a timestamp like the following:
Timestamp('2022-01-01 19:55:00')
How do i get the time difference to the next full hour (in minutes)?
So in this example the output should be 5 minutes.
You'll need to use the datetime lib :
from datetime import datetime, timedelta
def time_to_next_hour(timestamp):
current_time = datetime.strptime(str(timestamp), '%Y-%m-%d %H:%M:%S')
next_hour = current_time.replace(microsecond=0, second=0, minute=0) + timedelta(hours=1)
time_diff = next_hour - current_time
return int(time_diff.total_seconds() / 60)
print(time_to_next_hour(Timestamp('2022-01-01 19:55:00')))

python time now and before

how i can do the checking. so that if the time which i write in the h m s format hasnt yet come, add yesterdays date to it
for example:
now 00:10:15 , i input 00:15:15 bot write 2022-09-09 00:15:15
and if the time has come to add todays
for example:
now 00:10:15 , i input 00:10:00 , bot write 2022-09-10 00:10:00
from datetime import datetime, timezone
import time
from zoneinfo import ZoneInfo
import pytz
#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))
newYorkTz = pytz.timezone("Europe/Kiev")
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d ')
#date = datetime.today().strftime('%Y-%m-%d ')
from_date = str(input('time): '))
fulldate = timeInNewYork + from_date
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp()
print(epoch)
You need to add an if.. else statement to check if the input time has passed (compared to the actual time) or not. If so, you can use timedelta to add one day and get your timestamp.
Try this :
from datetime import datetime, timezone, timedelta
import time
from zoneinfo import ZoneInfo
import pytz
#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))
newYorkTz = pytz.timezone("Europe/Kiev")
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d')
#date = datetime.today().strftime('%Y-%m-%d ')
now = datetime.now(newYorkTz)
from_date = str(input('time): '))
my_datetime = datetime.strptime(from_date, "%H:%M:%S")
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
fulldate = timeInNewYork + ' ' + from_date
if (now > my_datetime):
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp()
else:
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S') + timedelta(days=-1)
epoch = dt.timestamp()
print(dt)
print(epoch)
>>> Test with a past time
time): 11:55:33
2022-09-10 11:55:33
1662803733.0
>>> Test with a future time
time): 19:00:33
2022-09-09 19:00:33
1662915633.0

How to remove 0:00:00 from the output of datetime.date() in python?

How to remove 0:00:00 from the output of datetime.date() function? For example:
import datetime
now = datetime.datetime.now()
year1 = now.strftime("%Y")
month2 = now.strftime("%m")
day3 = now.strftime("%d")
year = int(year1)
month = int(month2)
day = int(day3)
first_day = datetime.date(2021,8,1)
second_day = datetime.date(year,month,day)
daysleft = first_day - second_day
print(daysleft)
I get the output:
9 days, 0:00:00
If you didn't understand the question title, My main goal is to remove the 0:00:00 before the period (.). I've seen many other questions like this (in stack overflow/exchange and other websites), but it was nothing in python coding language.
You can get just the days by asking for the .days attribute of a datetime.timedelta object. E.g.:
print('{} days'.format(daysleft.days))
If your only goal is printing the output and you don't care about maintaining daysleft as a datetime object, you can always convert it to a string and .split() it like this:
print(str(daysleft).split(",")[0])
datetime has many useful functions and values
To get only days you can daysleft.days
print(f'{daysleft.days} days')
but you can also reduce other code to
now = datetime.datetime.now()
daysleft = first_day - now.date()
or
today = datetime.date.today()
daysleft = first_day - today
BTW:
If you need year, month, day as numbers then you can get it as
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
ms = now.microsecond
weekday = now.weekday() # 0 = monday, ..., 6 = sunday
weekday = now.isoweekday() # 1 = monday, ..., 7 = sunday
Other useful function timedelta
one_day = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = today - one_day
tomorrow = today + one_day
day_after_tomorrow = today + 2*one_day
Minimal working code with tkinter
import datetime
first_day = datetime.date(2021, 8, 1)
now = datetime.datetime.now()
daysleft = first_day - now.date()
today = datetime.date.today()
daysleft = first_day - today
print(f'{daysleft.days} days')
# ---
import tkinter as tk
root = tk.Tk()
lbl = tk.Label(root, text=f'{daysleft.days} days till {first_day}')
lbl.pack()
root.mainloop()

How can I use datefunction or put python date in below selenium coding.. Right now i am putting hardcoded value '2021-05-01' and 2021-05-31'

element = driver.find_element_by_id("txtStarttime")
driver.execute_script("arguments[0].removeAttribute('type')", element)
new_element = driver.find_element_by_id("txtStarttime")
driver.execute_script("arguments[0].setAttribute('value','2021-05-01')", new_element)
#'value','2021-05-01'
element2 = driver.find_element_by_id("txtEndtime")
driver.execute_script("arguments[0].removeAttribute('type')", element2)
new_element2 = driver.find_element_by_id("txtEndtime")
driver.execute_script("arguments[0].setAttribute('value','2021-05-31')", new_element2)
import time
time.strftime(('%Y-%m-%d'))
Out:
'2021-06-21'
Try relativedelta
from datetime import date
from dateutil.relativedelta import relativedelta
driver = webdriver.Chrome()
today = date.today()
d = today - relativedelta(months=1)
first_day = date(d.year, d.month, 1)
first_day = first_day.strftime('%Y-%m-%d')
last_day = date(today.year, today.month, 1) - relativedelta(days=1)
last_day = last_day.strftime('%Y-%m-%d')
print(first_day)
print(last_day)
Prints:
2021-05-01
2021-05-31
Then just send_keys with those values:
new_element = driver.find_element_by_id("txtStarttime")
new_element.send_keys(first_day)
new_element2 = driver.find_element_by_id("txtEndtime")
new_element2.send_keys(last_day)

Converting 12 hour format time string (with am/pm) into UTC in 24 hour format

I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)

Categories

Resources