How to show a notification when the previously entered date arrives - python

I'm trying to make a reminder app, but I can't find out how to show if the entered date is the current date. To give an example:
I added a reminder on December 19, 2021 at 17:45, and I want to know if this date is before today's date.

You can use datetime.datetime.strptime() to convert string to datetime object. Then you can calculate time delta with to check how much time is left.
import datetime
reminder = datetime.datetime.strptime('12/19/2021, 19:11:14',
"%m/%d/%Y, %H:%M:%S")
print(datetime.datetime.now()) # 2021-12-12 17:24:01.573420
time_delta = reminder - datetime.datetime.now()
print(time_delta.seconds) # 6432
print(time_delta.days) # 7
If the current date is after the reminder date, days will be negative.

You can use the python's builtin datetime module.
You can import it like this:
from datetime import datetime
To convert the reminder string to a date time object, you can use the strptime() function.
reminder_date = "December 19, 2021 at 17:45"
reminder = datetime.strptime(reminder_date, "%B %d, %Y at %H:%M")
Next, get the current datetime object.
current = datetime.now()
Finally, you can compare them using python's builtin comparison operators as follows.
if reminder < current:
print("passed")
else:
print("future")

Related

Extract each year, month, day, year from getctime , getmtime in Python

I want to extract the year month day hours min eachly from below value.
import os, time, os.path, datetime
date_of_created = time.ctime(os.path.getctime(folderName))
date_of_modi = time.ctime(os.path.getmtime(folderName))
Now I only can get like below
'Thu Dec 26 19:21:37 2019'
but I want to get the the value separtly
2019 // Dec(Could i get this as int??) // 26
each
I want to extract each year month day each time min value from date_of_created and date_of_modi
Could i get it? in python?
You can convert the string to a datetime object:
from datetime import datetime
date_of_created = datetime.strptime(time.ctime(os.path.getctime(folderName)), "%a %b %d %H:%M:%S %Y") # Convert string to date format
print("Date created year: {} , month: {} , day: {}".format(str(date_of_created.year),str(date_of_created.month),str(date_of_created.day)))
The time.ctime function returns the local time in string form. You might want to use the time.localtime function, which returns a struct_time object which contains the information you are looking for. As example,
import os, time
date_created_string = time.ctime(os.path.getctime('/home/b-fg/Downloads'))
date_created_obj = time.localtime(os.path.getctime('/home/b-fg/Downloads'))
print(date_created_string) # Mon Feb 10 09:41:03 2020
print('Year: {:4d}'.format(date_created_obj.tm_year)) # Year: 2020
print('Month: {:2d}'.format(date_created_obj.tm_mon)) # Month: 2
print('Day: {:2d}'.format(date_created_obj.tm_mday)) # Day: 10
Note that these are integer values, as requested.
time.ctime([secs])
Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 20 23:21:05 1993' representing local time.
If that's not what you want... use something else? time.getmtime will return a struct_time which should have the relevant fields, or for a more modern interface use datetime.datetime.fromtimestamp which... returns a datetime object from a UNIX timestamp.
Furthermore, using stat would probably more efficient as it ctime and mtime will probably perform a stat call each internally.
You can use the datetime module, more specifically the fromtimestamp() function from the datetime module to get what you expect.
import os, time, os.path, datetime
date_of_created = datetime.datetime.fromtimestamp(os.path.getctime(my_repo))
date_of_modi = datetime.datetime.fromtimestamp(os.path.getmtime(my_repo))
print(date_of_created.strftime("%Y"))
Output will be 2020 for a repo created in 2020.
All formats are available at this link

How to compare time/date in different formats?

Let's say I am pulling the date of a file using this command:
>> date_created = time.ctime(os.path.getctime(latest_file))
>> print (date_created)
Thu Aug 17 13:44:19 2017
How can I say compare this date to today or tomorrow for example? How can I pull out specifically Aug 17 and say:
psuedocode:
if (Aug 17 = today){
function()
}
else{
break
}
Essentially, I want to have a check whether or not the file was created today, and if it was then perform the function.
Let's say I am pulling the current date in this form:
date_time = time.strftime('%m-%d-%Y')
You can use datetime to convert the timestamp to a datetime.datetime object and check the date against today's date.
Example -
from datetime import datetime
date_created = datetime.fromtimestamp(os.path.getctime(latest_file))
if date_created.date() == datetime.now().date():
#Do your logic
You can use timedelta to get tomorrow or yesterday's datetime object. Example -
from datetime import timedelta
tomorrow = datetime.datetime.now() + timedelta(days=1)
Similarly, you can use -1 for yesterday and so on.

Check date is within one year python

I have a date string formatted like this: "2017-05-31T06:44:13Z".
I need to check whether this date is within a one year span from today's date.
Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.
from datetime import datetime
from dateutil.relativedelta import relativedelta
# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)
if today <= date_to_check <= one_year_from_now:
# do whatever
Use the datetime package together with timedelta:
import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)
and simply check if now-d > then.

Subtracting Dates With Python

I'm working on a simple program to tell an individual how long they have been alive.
I know how to get the current date, and get their birthday. The only problem is I have no way of subtracting the two, I know a way of subtracting two dates, but unfortunately it does not include hours, minutes, or seconds.
I am looking for a method that can subtract two dates and return the difference down to the second, not merely the day.
from datetime import datetime
birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329
Use UTC time otherwise age in seconds can go backwards during DST transition:
from datetime import datetime
born = datetime(1981, 12, 2) # provide UTC time
age = datetime.utcnow() - born
print(age.total_seconds())
You also can't use local time if your program runs on a computer that is in a different place (timezone) from where a person was born or if the time rules had changed in this place since birthday. It might introduce several hours error.
If you want to take into account leap seconds then the task becomes almost impossible.
When substracting two datetime objects you will get a new datetime.timedelta object.
from datetime import datetime
x = datetime.now()
y = datetime.now()
delta = y - x
It will give you the time difference with resolution to microsencods.
For more information take a look at the official documentation.
Create a datetime.datetime from your date:
datetime.datetime.combine(birthdate, datetime.time())
Now you can subtract it from datetime.datetime.now().
>>> from datetime import date, datetime, time
>>> bday = date(1973, 4, 1)
>>> datetime.now() - datetime.combine(bday, time())
datetime.timedelta(14392, 4021, 789383)
>>> print datetime.now() - datetime.combine(bday, time())
14392 days, 1:08:13.593813
import datetime
born = datetime.date(2002, 10, 31)
today = datetime.date.today()
age = today - born
print(age.total_seconds())
Output: 463363200.0
Since DateTime.DateTime is an immutable type method like these always produce a new object the difference of two DateTime object produces a DateTime.timedelta type:
from datetime import date,datetime,time,timedelta
dt=datetime.now()
print(dt)
dt2=datetime(1997,7,7,22,30)
print(dt2)
delta=dt-dt2
print(delta)
print(int(delta.days)//365)
print(abs(12-(dt2.month-dt.month)))
print(abs(dt.day))
The output timedelta(8747,23:48:42.94) or what ever will be days when u test the code indicates that the time delta encodes an offset of 8747 days and 23hour and 48 minute ...
The Output
2021-06-19 22:27:36.383761
1997-07-07 22:30:00
8747 days, 23:57:36.383761
23 Year
11 Month
19 Day

How do I convert a datetime to date?

How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?
Use the date() method:
datetime.datetime.now().date()
From the documentation:
datetime.datetime.date()
Return date object with same year, month and day.
You use the datetime.datetime.date() method:
datetime.datetime.now().date()
Obviously, the expression above can (and should IMHO :) be written as:
datetime.date.today()
You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()
Answer updated to Python 3.7 and more
Here is how you can turn a date-and-time object
(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)
into a date object (aka datetime.date object):
from datetime import datetime
#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)
# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)
# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()
And just to be clear, if you print those elements, here is the output :
print(datetime_element)
2020-07-10 12:56:54.324893
print(date_element)
2020-07-10
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
import time
import datetime
# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
start = end - datetime.timedelta(days=numdays+1)
end = int(time.mktime(end.timetuple()))
start = int(time.mktime(start.timetuple()))
# 86400 s = 1 day
return xrange(start, end, 86400)
# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
print datetime.datetime.fromtimestamp(dt).date()
I use data.strftime('%y-%m-%d') with lambda to transfer column to date
Solved: AttributeError: 'Series' object has no attribute 'date'
You can use as below,
df["date"] = pd.to_datetime(df["date"]).dt.date
where in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)
If you are using pandas then this can solve your problem:
Lets say that you have a variable called start_time of type datetime64 in your dataframe then you can get the date part like this:
df.start_time.dt.date

Categories