Skip to content

Instantly share code, notes, and snippets.

@chrisgrande
Created August 31, 2023 20:26
Show Gist options
  • Save chrisgrande/088c10a4b7a642fe356e72f169dca1e5 to your computer and use it in GitHub Desktop.
Save chrisgrande/088c10a4b7a642fe356e72f169dca1e5 to your computer and use it in GitHub Desktop.
A python version of the Ruby 5.day.ago syntax.
#!/usr/bin/env python3
from datetime import datetime, timedelta
class TimeDeltaWrapper:
def __init__(self, delta):
self.delta = delta
def ago(self):
return datetime.now() - self.delta
class TimeInterval:
def __init__(self, value):
self.value = value
@property
def minutes(self):
return TimeDeltaWrapper(timedelta(minutes=self.value))
@property
def hours(self):
return TimeDeltaWrapper(timedelta(hours=self.value))
@property
def days(self):
return TimeDeltaWrapper(timedelta(days=self.value))
@property
def weeks(self):
return TimeDeltaWrapper(timedelta(weeks=self.value))
@property
def months(self):
return TimeDeltaWrapper(timedelta(weeks=self.value * 4))
@property
def years(self):
return TimeDeltaWrapper(timedelta(weeks=self.value * 52))
# Usage
fifty_minutes_ago = TimeInterval(50).minutes.ago()
print(f"50 minutes ago: {fifty_minutes_ago}")
four_hours_ago = TimeInterval(4).hours.ago()
print(f"4 hours ago: {four_hours_ago}")
five_days_ago = TimeInterval(5).days.ago()
print(f"5 days ago: {five_days_ago}")
two_weeks_ago = TimeInterval(2).weeks.ago()
print(f"2 weeks ago: {two_weeks_ago}")
three_months_ago = TimeInterval(3).months.ago()
print(f"3 months ago: {three_months_ago}")
one_year_ago = TimeInterval(1).years.ago()
print(f"1 year ago: {one_year_ago}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment