Compare only today's date without hours/min/sec - python

I want to compare todays time with another new time without hour/min or seconds. Ignore hour and minutes...
In other words if both days are the same no matter hours or minutes it is ok (Extra) otherwise it is not good (Too old)... I tried but even with the same day still continue to compare with hour/min and sec. How can I do it?
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")`

Compare using only the date component of datetime, accessible via the .date() attribute:
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate.date() == newsdate.date():
print("Extra")
else:
print("Too old")
The above can also be reworded as follows (perhaps to aid in readability for others):
from datetime import date, datetime
currentdate: date = date.today()
print(currentdate)
date_string = "Oct-26-2021"
newsdate: date = datetime.strptime(date_string, "%b-%d-%Y").date()
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")

Related

How can I make a list of last two digits of year plus month

Can I get some help to create a list of days and months in the folowing format:
collection = ['2108', '2109', '2110', '2111', '2112', '2201']
I am trying in this way:
def make_collections(start_date: Date, end_date: Date):
result = []
date = start_date
while True:
if start_date >= end_date:
return result
date = date.strftime('%y%m%d%H%M%S')
result.append(date[:4])
date = (date.strptime(date, '%y%m%d%H%M%S')) + timedelta(days=1)
# test = MakeDataFrame()
# test.run()
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
But it doesn't work.
I want to give a start date and end date as an argument in function and make a list as I mentioned above with year and month.
Can I get some help to make a a simple function with start and end date as an arguments?
Thanks
I revised your code a little bit, so that the code will print what you expected. I used dateutil.relativedelta module because timedelta provide only day-based delta. dateutil.relativedelta support to calculate month and year differences.
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
def make_collections(start_date, end_date):
result = []
while start_date <= end_date:
result.append(str(start_date.year)[2:] + str(start_date.month).zfill(2))
start_date += relativedelta(months=1)
return result
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
#['2101', '2102', '2103', '2104', '2105', '2106', '2107', '2108', '2109', '2110', '2111', '2112', '2201']

Compare the time of datetime.now() object with time string

Using Rouble's suggestion and Maulik Gangani's example based on that suggestion:
How do I determine if current time is within a specified range using Python's datetime module?
I have two time strings that have been converted into a datetime object using .strptime as follows:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
I have a datetime object for time now:
timeNow = datetime.now()
My problem is that unless I convert timeNow (datetime object) into a string and then back again using .strptime , the script will not work:
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
Full code:
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M')
timeStart = datetime.strptime(timeStart, '%H%M')
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
My question is, how do I format timeNow = datetime.now() so that I can compare it against a string in 24hr format '0000' without having to convert datetime.now() to a string and back again?
The reason why your code is not working, it's because apart from time, datetime (as the name suggests) holds also information about the date.
When you run the following code:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
The hour and minute is converted, but the rest (the "date" part) is assumed to be epoch:
repr(timeStart)
# Output: 'datetime.datetime(1900, 1, 1, 3, 0)'
When you run datetime.now(), however, that always assumes the current time + date:
>>> datetime.now()
datetime.datetime(2020, 7, 17, 8, 25, 18, 270848)
The reason why converting to string, and back from string works, is because when you convert your datetime to a string with the format '%H%M, you lose the date part in the resulting string. Converting back from that, there's only hour and minutes to read, so you're losing the date part.
Effectivelly, you should be using datetime.time, instead of datetime.datetime to compare time.
After reading using strptime, try using the .time() method to only extract the time part and lose the date part:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M').time()
And same for the timeNow part:
timeNow = datetime.now().time()
If you call datetime.strptime, a default date is added if you only supply a time string. datetime.now() will have today's date. You can remove that by using only the time part of the datetime object - which you get by calling the time() method, e.g.
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M').time()
timeStart = datetime.strptime(timeStart, '%H%M').time()
timeNow = datetime.now().time()
print(isNowInTimePeriod(timeStart, timeEnd, timeNow))
# True (my current time is 0823)

Calculating time intervals in Python, a more smarter way

was trying to calculate and a timedelta element with a str concatente, finally got it but feel there should be a smarter way to do this, any idea pls. here are my lines of code:
import datetime
import time
currentTime = datetime.datetime.now()
print("The time now is " + currentTime.strftime('%I:%M %p'))
realTime = currentTime.strftime('%I:%M:%S %p')
realTime was necessary to convert the datetime currentTime to a str to feed to strptime
print(realTime)
meetTime = input("Please input the meeting time in 12hrs timing")
# timeToMeet = datetime.datetime.strptime('11:50PM', '%I:%M%p').time()
timeToMeet = datetime.datetime.strptime(meetTime, '%I:%M%p')
tried both static and input time and they both worked
print(timeToMeet.strftime('%H:%M %p'))
timeNow = datetime.datetime.strptime(realTime, '%I:%M:%S %p')
print("The time now is " + timeNow.strftime('%I:%M%p'))
tdelta = timeToMeet - timeNow
print("Please, your meeting starts in " + str(tdelta))
print(tdelta)

How to replace the day in a date with another date?

I'm trying to replace the day in my if statement for my date but I keep getting this output for my year.
05/15/5 besides 05/15/2020 . Code is below:
today_date = datetime.datetime.now()
date = today_date.date()
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
mmonth = date.month
myear = date.year
mdate = date.day
if mdate < 7:
m0weekend = formatted_date.replace(str(myear),str(mmonth),1)
else:
m0weekend = formatted_date.replace(str(myear),str(mmonth),15)
it's easier to replace the day before converting to a string:
date = date.replace(day=1)
or, in your case:
if mdate < 7:
m0weekend = date.replace(day=1)
else:
m0weekend = date.replace(day=15)
formatted_date is actually a string.
You are using the str.replace() method not the datetime.date.replace() method.
import datetime
today_date = datetime.datetime.now()
pre_formatted_date = today_date.date()
mmonth = pre_formatted_date.month
myear = pre_formatted_date.year
mdate = pre_formatted_date.day
if mdate < 7:
pre_formatted_date = pre_formatted_date.replace(day=1)
else:
pre_formatted_date = pre_formatted_date.replace(day=15)
print(pre_formatted_date)
formatted_date = pre_formatted_date.strftime("%m/%d/%Y")
print(formatted_date)
Which has the following output:
2020-05-15
05/15/2020
You might get today datetime.date directly from datetime rather than creating datetime.datetime and converting to date. After you have today you might create needed datetime.date and turn it into str, i.e.:
import datetime
today = datetime.date.today()
date = datetime.date(today.year, today.month, 1 if today.day < 7 else 15)
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
print(formatted_date) # 05/15/2020

Getting dates in python between a past datestamp and the present

Language Python
I am wondering if anyone can help me print out some dates.
i cam trying to create a loop in which i pass in a date say 01/1/2017 and the loop will then output the first and last day in every month between then and the present day.
Example
01/01/2017
31/01/2017
01/02/2017
28/02/2017
etc
Any help will be appreciated
Hope this will help,
Code:
from datetime import date
from dateutil.relativedelta import relativedelta
from calendar import monthrange
d1 = date(2018, 2, 26)
d2 = date.today()
def print_month_day_range(date):
first_day = date.replace(day = 1)
last_day = date.replace(day = monthrange(date.year, date.month)[1])
print (first_day.strftime("%d/%m/%Y"))
print (last_day.strftime("%d/%m/%Y"))
print_month_day_range(d1)
while (d1 < d2):
d1 = d1 + relativedelta(months=1)
print_month_day_range(d1)
Output:
01/02/2018
28/02/2018
01/03/2018
31/03/2018
...
01/07/2018
31/07/2018
you can use calendar module. Below is the code:
import datetime
from calendar import monthrange
strt_date = '01/1/2017'
iter_year = datetime.datetime.strptime(strt_date, '%m/%d/%Y').year
iter_month = datetime.datetime.strptime(strt_date, '%m/%d/%Y').month
cur_year = datetime.datetime.today().year
cur_month = datetime.datetime.today().month
while cur_year > iter_year or (cur_year == iter_year and iter_month <= cur_month):
number_of_days_in_month = monthrange(iter_year, iter_month)[1]
print '/'.join([str(iter_month) , '01', str(iter_year)])
print '/'.join([str(iter_month), str(number_of_days_in_month), str(iter_year)])
if iter_month == 12:
iter_year += 1
iter_month = 1
else:
iter_month += 1
this could work, as long as the first date you give is always the first of the month
from datetime import datetime
from datetime import timedelta
date_string = '01/01/2017'
date = datetime.strptime(date_string, '%d/%m/%Y').date()
today = datetime.now().date()
months = range(1,13)
years = range(date.year, today.year + 1)
for y in years:
for m in months:
new_date = date.replace(month=m, year=y)
last_day = new_date - timedelta(days=1)
if (date < new_date) & (new_date <= today):
print last_day.strftime('%d/%m/%Y')
print new_date.strftime('%d/%m/%Y')
elif (date <= new_date) & (new_date <= today):
print new_date.strftime('%d/%m/%Y')
This code would print the first and last days of all months in a year.
Maybe add some logic to iterate through the years
import datetime
def first_day_of_month(any_day):
first_month = any_day.replace(day=1)
return first_month
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
return next_month - datetime.timedelta(days=next_month.day)
for month in range(1, 13):
print first_day_of_month(datetime.date(2017, month, 1))
print last_day_of_month(datetime.date(2017, month, 1))

Categories