How to compare time/date in different formats? - python

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.

Related

How to show a notification when the previously entered date arrives

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")

Wrong output on adding 2 days in current date or today date using python

I am adding 2 days in current date or today date using python but getting wrong output, please at look at code below i used ::
from datetime import date
from datetime import timedelta
time_diff =str(timedelta(days=2))
d =str(date.today().strftime("%Y-%m-%d") ) + time_diff
print(d.split("day")[0])
OUTPUT ::2020-04-262
i think it should show the output ::2020-04-28.
You don't need all those str() calls. You want to add the time delta to a time, you don't want to add two strings together (that just concatenates).
Just add the time delta to the date:
from datetime import timedelta
time_diff = timedelta(days=2)
a_date = date.today() + time_diff
a_date_string = a_date.strftime("%Y-%m-%d")
print(a_date_string)
# 2020-04-28

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

Python 3.6 Weekday

I have a combination date/time string 20180104 06:09:36.234 from which I want to find the weekday in python, expecting to get the result for for the date (which is 04 January 2018) as "4" (ie Thursday) . Have searched far and wide to no avail.Can anyone help please?
Thanks CJ
See explanation of datetime.strptime
from datetime import datetime
date_string = '20180104 06:09:36.234'
date = datetime.strptime(date_string, '%Y%m%d %H:%M:%S.%f')
print(date.isoweekday()) # 4
Finally worked it out by various combinations of functions:
Identify year, month, date,
Convert to integer,
Use datetime module.
import datetime
DateTime = '20180104 06:09:36.234'
Weekday = datetime.date(int(DateTime[0:4]), int(DateTime[5:6]),
int(DateTime[7:8])).weekday()
print("Weekday = " , Weekday)
Weekday = 3
Is there a better way??

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.

Categories