Skip to content

Instantly share code, notes, and snippets.

@carlosmaniero
Last active October 6, 2021 13:27
Show Gist options
  • Save carlosmaniero/b18e3c9c8c48d680d88dc86870c67378 to your computer and use it in GitHub Desktop.
Save carlosmaniero/b18e3c9c8c48d680d88dc86870c67378 to your computer and use it in GitHub Desktop.
Python Date
import datetime
from service.time_converter import iso_format_to_unix_time
DAYS_OF_THE_WEEK = 7
def current_week_start(of = None):
date_to_compare = datetime.datetime.now()
if of is not None:
date_to_compare = datetime.datetime.utcfromtimestamp(of)
current_weekday_starting_in_one = date_to_compare.weekday() + 1
sunday_time_delta = datetime.timedelta(
current_weekday_starting_in_one % DAYS_OF_THE_WEEK
)
sunday = date_to_compare - sunday_time_delta
sunday_without_time = sunday.date()
return iso_format_to_unix_time(sunday_without_time.isoformat())
def previous_week_start(of = None):
current_sunday = datetime.datetime.utcfromtimestamp(current_week_start(of))
previous_sun = (current_sunday - datetime.timedelta(DAYS_OF_THE_WEEK)).date()
return iso_format_to_unix_time(previous_sun.isoformat())
from service.date_service import current_week_start, previous_week_start
from unittest import TestCase
from service.time_converter import iso_format_to_unix_time
import datetime
class TestDateService(TestCase):
def test_it_returns_the_previous_week_start(self):
previous_week = previous_week_start(iso_format_to_unix_time('2021-08-23T08:55:00'))
self.assertEqual(previous_week, iso_format_to_unix_time(datetime.date(2021, 8, 15).isoformat()))
self.assertTrue(previous_week_start() < iso_format_to_unix_time(datetime.datetime.today().isoformat()))
def test_it_returns_the_current_week_start(self):
current_week = current_week_start(iso_format_to_unix_time('2021-08-23T08:55:00'))
self.assertEqual(current_week, iso_format_to_unix_time(datetime.date(2021, 8, 22).isoformat()))
self.assertTrue(current_week_start() < iso_format_to_unix_time(datetime.datetime.today().isoformat()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment