16

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.

Will
  • 24,082
  • 14
  • 97
  • 108
Luke B
  • 163
  • 1
  • 1
  • 4
  • 2
    When you say "last three months", what do you mean? Calendar months? 90 days? – TM. Apr 27 '11 at 03:57
  • 3
    If you can figure out how to manipulate time using only Python code, I know some physicists who would like to speak with you. ;D – kqnr Apr 27 '11 at 04:30
  • related: [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/q/26313520/4279) – jfs Oct 20 '15 at 14:16

8 Answers8

29
time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
26

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
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
  • 1
    Instead of `duration.days` I'd suggest `duration.total_seconds()/(24*60*60)` so it's more precise -- `.days` just pulls put the number of days effectively truncating so that 1 day 12 hours becomes 1 day, and leads to unintended off by one errors. – wij Nov 01 '19 at 18:17
6

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
4

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"
Pavan Gupta
  • 17,663
  • 4
  • 22
  • 29
  • the core issue here is how many days constitute 3 months here. Your answer doesn't address it. – jfs Oct 20 '15 at 14:15
  • I would use .getmtime() instead, in case the file has been modified since it has been created. – rouble Dec 22 '20 at 16:45
2

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 )

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
2

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.

A Lee
  • 7,828
  • 4
  • 35
  • 49
0

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)

Balaji D
  • 111
  • 1
  • 6
0

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))
rouble
  • 16,364
  • 16
  • 107
  • 102