This question already has answers here:
How to compare times of the day?
(8 answers)
Closed 3 years ago.
I'm trying to compare two time in python:
from datetime import time, datetime
start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
if (current_time == start):
print("Time Matched")
Now when i'm running the code and when time reaches above mentioned start time, it does not prints "Time is matched" Kindly help me out in what im trying to do with this code is that when start time matches my laptop time i'm trying to execute some code , buy i'm not able to do so.
**Your PC Note down time with millisecond that's why you are not able to get desired result **
If You Provide second in datetime obj then -\
from datetime import time, datetime
start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
start_str=str(start)
current_str=str(surrent_time)
if(start_str==current_str):
print(match)
**General Method **
if we want to match particular part This is 23 hour format if you want 12 hour format you can find diff parameter answer
start = datetime(2020, 1 , 18, 9,30)
current = datetime.now()
start_year=start.strftime("%Y")
start_month=start.strftime("%m")
start_day=start.strftime("%H")
start_hours=start.strftime("%H")
start_min=start.strftime("%M")
print(start_year,start_month,start_day,start_hours,start_min)
current_year=current.strftime("%Y")
current_month=current.strftime("%m")
current_day=current.strftime("%H")
current_hours=current.strftime("%H")
current_min=current.strftime("%M")
print(current_year,current_month,current_day,current_hours,current_min)
if((start_year==current_year) and (start_month==current_month) and (start_day==current_day) and (start_hours==current_hours) and (start_min==current_min)):
print("match")
Related
This question already has answers here:
How to add hours to current time in python
(4 answers)
Closed 3 years ago.
I want to get current time and add it with an integer of hours. Example now is 11.00pm, May 12, 2019. I want to add 3 hours more. So the result would be 2.00 am May 13, 2019. Please help me to datetime + hours(integer type)
import datetime
currentDT = datetime.datetime.now()
print('Now is: '+ str(currentDT))
hours = int(input()) #any hours you want
result = currentDT + hours #it will get the errors here
Use datetime.now to obtain the current time, and add a datetime.timedelta:
from datetime import datetime, timedelta
n_hours = 3
date = datetime.now() + timedelta(hours=n_hours)
print(datetime.now())
# 2019-05-12 19:16:51.651376
print(date)
# 2019-05-12 22:16:51.464890
This question already has answers here:
Generating dates to the days of a week in Python?
(3 answers)
Python - Add days to an existing date
(1 answer)
Adding days to a date in Python
(16 answers)
Closed 3 years ago.
I have a code that can tell the weather in entered location.
I want to make an option to print the weather for the next 3 days ,I need to send to my function 3 dates (with a loop), every time different date, how can I send dates of next 3 days from current day?
#This is my function
def weather(city, date):
#This is the part where I send it from the main to the function:
city = 'Paris'
while(i < 4):
i += 1
weather(city.lower(), dd/mm/yyyy)# Here instead of "dd/mm/yyyy" I need to send every time the next date from today.
Use datetime.timedelta(days=1) to increment your day by 1 as follows, you can pass this date to your function
import datetime
curr_date = datetime.datetime.now()
for i in range(4):
curr_date += datetime.timedelta(days=1)
print(curr_date)
#2019-04-19 22:01:29.503352
#2019-04-20 22:01:29.503352
#2019-04-21 22:01:29.503352
#2019-04-22 22:01:29.503352
The simplest way to generate a date range is to use pandas.date_range as
import pandas as pd
dates = pd.date_range('2019-04-10', periods=3, freq='D')
for day in dates:
weather(city, day)
Or you may insist on a loop for next days, you can use datetime.timedelta
from datetime import date, timedelta
one_day_delta = timedelta(1)
day = datetime.date(2019, 4, 19)
for i in range(3)
day += one_day_delta
weather(city, day)
This question already has answers here:
Days between two dates? [duplicate]
(4 answers)
Closed 5 years ago.
I need to design a code that will automatically generate the date X number of days from current date.
For that, I currently have a function that returns an epoch timestamp, which I then add the fixed number of days in seconds. However, I am currently stuck there and do not know how to convert the epoch timestamp into a Gregorian calendar date format (DD/MM/YYYY HH:MM). Displaying time is optional, can be rounded to the nearest day.
A way to do this without using an epoch timestamp and directly getting the current date in a readable format, printing it, and adding X days to it before generating the second date, is also fine, but I have no idea how that would work.
Any help/input would be much appreciated. Thanks in advance.
You can use timedelta.
import datetime as dt
x = 5 # Days offset.
now = dt.datetime.now()
>>> now + dt.timedelta(days=x)
datetime.datetime(2017, 12, 2, 21, 10, 19, 290884)
Or just using days:
today = dt.date.today()
>>> today + dt.timedelta(days=x)
datetime.date(2017, 12, 2)
Easy enough to convert back to a string using strftime:
>>> (today + dt.timedelta(days=x)).strftime('%Y-%m-%d')
'2017-12-02'
import datetime
x = 5
'''
Date_Time = datetime.datetime.now()#It wil give Date & time both
Time = datetime.datetime.now().time()#It will give Time Only
'''
Date = datetime.datetime.now().date()#It will give date only
print(Date + datetime.timedelta(days=x))#It will add days to current date
Output:
2017-12-03
This question already has answers here:
How to compare times of the day?
(8 answers)
python time subtraction
(1 answer)
Closed 6 years ago.
I want to write a simple timesheet script. My input file looks like
9:00 17:00
10:45 12:35
11:00 15:00
I would like to read it in, compute the number of hours worked per day and then sum those hours up. When the day started before 12:00 and ended after 13:00 I would like to subtract half an hour too for lunch break.
My attempt so far is:
import sys
from datetime import datetime
gap = datetime.strptime('00:30','%H:%M')
hours = []
for line in sys.stdin:
(start_time,end_time) = line.split()
start_time = datetime.strptime(start_time, '%H:%M')
end_time = datetime.strptime(end_time, '%H:%M')
#if start_time before 12:00 and end_time after 13:00 then subtract gap
hours.append(end_time-start_time)
print sum(hours)
I don't know how to get the if statement line to work and summing the hours doesn't seem to work either as you can't sum datetime.timedelta types.
Thanks to the link in the comments, replacing sum(hours) with reduce(operator.add, hours) works.
The remaining part is how to test if start_time is before 12:00 and end_time is after 13:00 and if so to reduce the timedelta by half an hour.
You are using incorrect code (and syntax) in your if statement.
if start_time < datetime.strptime('12:00', '%H:%M') and end_time > datetime.strptime('13:00', '%H:%M'):
delta_hours = end_time.hour - start_time.hour)
delta_minutes = end_time.minutes - start_time.minutes)
# Do whatever your want with it now.
# Substraction of the break is not implemented in this example, it depends on how you want to save it.
Time delta might be worth looking into as well, it can use basic operations like
a = timedelta(...)
b = timedelta(...)
c = b - a - gap
This question already has answers here:
What's the best way to find the inverse of datetime.isocalendar()?
(8 answers)
Closed 8 years ago.
I'm writing a script where the user needs to input a week number and a procedure will be ran based on that. However, I ran into a small issue, I know I can get week numbers via something like this:
>>> a=datetime.datetime.now()
>>> a
datetime.datetime(2015, 1, 22, 15, 51, 57, 820058)
>>> a.isocalendar()[1]
4
But I can't find how to do it backwards. Also, the date I require has to be Sunday of that week at 6:00am. Once I have that datetime element I can just do
begin_date = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
To get the format I want. I'm still missing the step to get the date. Any thoughts?
We create an initial datetime of for 2015 (2014-12-28 6:00:00 --1st sunday of 1st week), and a timedelta object of 7 days:
w0 = datetime.datetime(2014,12,28,6)
d7 = datetime.timedelta(7)
Then you can simply add multiples of the timedelta object to the initial date like so (n would be your week number):
w0+(d7*n)
>>> now = datetime.datetime.now()
>>> start = datetime.datetime(2015, 1,1)
>>> (now - start).days // 7
3