I'm curious about manipulating time in Python. I can get the (last modified) age of a file using the os.path.getmtime() function as such:
import os.path, time
os.path.getmtime(oldLoc)
I need to run some kind of test to see whether this time is within the last three months or not, but I'm thoroughly confused by all the available time options in Python.
Can anyone offer any insight? Kind Regards.
time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
You can use a bit of datetime arthimetic here for the sake of clarity.
>>> import datetime
>>> today = datetime.datetime.today()
>>> modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('yourfile'))
>>> duration = today - modified_date
>>> duration.days > 90 # approximation again. there is no direct support for months.
True
To find whether a file is older than 3 calendar months, you could use dateutil.relativedelta:
#!/usr/bin/env python
import os
from datetime import datetime
from dateutil.relativedelta import relativedelta # $ pip install python-dateutil
three_months_ago = datetime.now() - relativedelta(months=3)
file_time = datetime.fromtimestamp(os.path.getmtime(filename))
if file_time < three_months_ago:
print("%s is older than 3 months" % filename)
The exact number of days in "last 3 months" may differ from 90 days in this case. If you need 90 days exactly instead:
from datetime import datetime, timedelta
three_months_ago = datetime.now() - timedelta(days=90)
If you want to take into account the changes in the local utc offset, see Find if 24 hrs have passed between datetimes - Python.
I was looking for something similar and came up with this alternative solution:
from os import path
from datetime import datetime, timedelta
two_days_ago = datetime.now() - timedelta(days=2)
filetime = datetime.fromtimestamp(path.getctime(file))
if filetime < two_days_ago:
print "File is more than two days old"
If you need to have the exact number of days you can use the calendar module in conjunction with datetime, e.g.,
import calendar
import datetime
def total_number_of_days(number_of_months=3):
c = calendar.Calendar()
d = datetime.datetime.now()
total = 0
for offset in range(0, number_of_months):
current_month = d.month - offset
while current_month <= 0:
current_month = 12 + current_month
days_in_month = len( filter(lambda x: x != 0, c.itermonthdays(d.year, current_month)))
total = total + days_in_month
return total
And then feed the result of total_number_of_days() into the code that others have provided for the date arithmetic.
1 day = 24 hours = 86400 seconds. Then 3 months is roughly 90 days which is 90 * 86400 seconds. You can use this information to add/subtract time. Or you can try the Python datetime module for date maths. (especially timedelta )
This is to know whether a date is 3 months older
from datetime import date, timedelta
time_period=date.today()-date(2016, 8, 10) < timedelta(days = 120)
Here is a generic solution using time deltas:
from datetime import datetime
def is_file_older_than (file, delta):
cutoff = datetime.utcnow() - delta
mtime = datetime.utcfromtimestamp(os.path.getmtime(file))
if mtime < cutoff:
return True
return False
To detect a file older than 3 months we can either approximate to 90 days:
from datetime import timedelta
is_file_older_than(filename, timedelta(days=90))
Or, if you are ok installing external dependencies:
from dateutil.relativedelta import relativedelta # pip install python-dateutil
is_file_older_than(filename, relativedelta(months=3))
Related
I am using the datetime Python module. I am looking to calculate the date 3 months from the input date. Can you help me to get out of this issue.Thanks in advance
import datetime
today = "2022-02-24"
three = today + datetime.timedelta(30*3)
print (three)
Also I tried using "relativedelta"
You can't add a timedelta to a string, you need to add it to a datetime instance
Note that 90 days, isn't really 3 months
from datetime import datetime, timedelta
today = "2022-02-24"
three = datetime.strptime(today, "%Y-%m-%d") + timedelta(30 * 3)
print(three) # 2022-05-25 00:00:00
three = datetime.today() + timedelta(30 * 3)
print(three) # 2022-05-24 21:32:35.048700
With relativedelta of dateutil package, you can use:
from dateutil.relativedelta import relativedelta
from datetime import date
three = date.today() + relativedelta(months=3)
Output:
>>> three
datetime.date(2022, 5, 23)
Is there some library or built-in to compare two timezones? What I want is the offset of hours between two timezones
For example:
hours = diff_timezones("America/Los_Angeles", "America/Sao_Paulo")
print(hours) # -> 3
FYI: Python 3.9+ ships with zoneinfo in its standard library, while dateutil (below) is a third-party package available on PyPI as python-dateutil.
Using dateutil.tz.gettz:
from datetime import datetime, timedelta
from dateutil.tz import gettz
def diff_timezones(tz1: str, tz2: str) -> timedelta:
zero = datetime.utcfromtimestamp(0)
diff = zero.replace(tzinfo=gettz(tz1)) - zero.replace(tzinfo=gettz(tz2))
return diff
Sample usage:
>>> diff_timezones('America/Los_Angeles', 'America/Sao_Paulo')
datetime.timedelta(seconds=18000)
The result here is a datetime.timedelta instance. To get a float of hours:
>>> td.total_seconds() / (60 * 60)
5.0
CAUTION: I don't believe this would take into account DST since it uses a fixed datetime of the Unix epoch (1970-01-01), so it might be off in cases where one area obeys DST and another does not. To account for that you might be able to use the current timestamp as a reference date instead.
This should work.
and here's a great blog about timezones and datetime: Blog
import datetime, pytz
d_naive = datetime.datetime.now()
timezone_a = pytz.timezone("America/Los_Angeles")
timezone_b = pytz.timezone("America/New_York")
d_aware_a = timezone_a.localize(d_naive)
d_aware_b = timezone_b.localize(d_naive)
difference = d_aware_a - d_aware_b
print(difference.total_seconds() / 60 / 60 ) # seconds / minutes
Is there any function in python that can generate date for example 4 weeks from now or given date?
I've gone through documentation from datetime modeule but couldnt find any example that can support my question.
four_weeks = datetime.timedelta(days=4*7)
dt = datetime.datetime.now()
print(dt + four_weeks)
Here you go:
from datetime import timedelta
from datetime import datetime
today = datetime.today()
print(today + timedelta(weeks=1))
I think the thing you're looking for is timedelta.
from datetime import timedelta
def add_weeks(dt, n_weeks):
n_days = 7 * n_weeks
return dt + timedelta(days=n_days)
In python datetime module has a class called datetime which represents a date + time, an point on time line. There is another class called timedelta that represents difference between two dates (datetiems).
You can add a date with a timedelta.
example code:
from datetime import datetime, timedelta
now = datetime.now()
duration = timedelta(days=28)
target = now + duration
print(target)
Given two dates, I would like to generate a list of dates with a fixed time length in between one another using datetime, starting from the later date.
For instance, given 01/01/2018 and 01/09/2018 and time interval of 2 months the output would be:
[01/01/2018, 01/03/2018, 01/05/2018, 01/07/2018, 01/09/2018]
For an interval of 3 months:
[01/03/2018, 01/06/2018, 01/09/2018]
I cannot just subtract months using the .replace method on a datetime object since going from a 31 days month to a 30 days month would return an error.
I think relativedeleta module can help you on this - pip install python-dateutil
from dateutil.relativedelta import *
import datetime
date1 = datetime.datetime.strptime('01/01/2018', "%d/%m/%Y").date()
date2 = datetime.datetime.strptime('01/09/2018', "%d/%m/%Y").date()
f = [(date1 + relativedelta(months=i)).strftime("%d/%m/%Y") for i in range(date1.month, date2.month,2)]
Result will be - ['01/02/2018', '01/04/2018', '01/06/2018', '01/08/2018']
You did specify datetime, but if you're interested,
a time.localtime object can be broken down like so:
import time
secSinceEpoch = time.time()
currentTime = time.localtime(secSinceEpoch)
month = currentTime.tm_mon
day = currentTime.tm_mday
year = currentTime.tm_year
hour = currentTime.tm_hour
min = currentTime.tm_min
sec = currentTime.tm_sec
From here you could perform operations on specific parts of the date/time...
I'd like to write a function which:
takes in parameter: a number of months (int)
returns the year (int) and the month (int) of the timedelta between now and the number of input months.
Example : we are in may 2014, so:
myfunc(0) should return (2014, 5)
myfunc(12) should return (2013, 5)
myfunc(5) should return (2013, 12)
etc.
There is lots of documentation about datetime and calendar, so much that I'm a bit lost. Thanks for help.
Note: I need to get an accurate way to do it, not an approximation :)
import datetime
def myfunc(num_of_months):
today = datetime.date.today()
num_of_months = today.year * 12 + today.month - 1 - num_of_months
year = num_of_months / 12
month = num_of_months % 12 + 1
return year, month
from time import strftime, localtime, time
from calendar import monthrange
def uberdate(n):
if n == 0: return strftime('%Y, %m').split(', ')
month = int(strftime('%m'))
aDay = 60*60*24
offset = aDay # One day to start off with
for i in range(0, n):
while int(strftime('%m', localtime(time()-offset))) == month:
offset = offset+aDay
month = int(strftime('%m', localtime(time()-offset)))
return strftime('%Y, %m', localtime(time()-offset)).split(', ')
print(uberdate(5))
This produces:
[torxed#archie ~]$ python test.py
[2013, 12]
Don't know why i got the downvote, but to quote OP:
Example : we are in may 2014, so:
myfunc(5) should return (2013, 12) etc.
And this is what my function produces...
Feedback people, give it before downvoting randomly.
You can use python-dateutil module for this. https://pypi.python.org/pypi/python-dateutil
def return_year_date(delta_month):
from datetime import date
from dateutil.relativedelta import relativedelta
new_date = date.today() + relativedelta(months= -delta_month)
return new_date.year, new_date.month
EDITED (Changed the month addition to make the accuracy perfect)
Now you can put negative number of months and get past dates
I think this is what youre looking for
import datetime
from dateutil.relativedelta import *
def calculate_date(number_months):
time_now = datetime.datetime.now() # Get now time
time_future = time_now + relativedelta(months=+number_months) # Add months
return time_future.year,time_future.month #Return year,month
I've tested this script in my coputer and works perfectly
>>> calculate_data(5)
(2014, 10)