|
| 1 | +""" |
| 2 | +
|
| 3 | +Odd or Even Day |
| 4 | +Given a timestamp (number of milliseconds since the Unix epoch), return: |
| 5 | +
|
| 6 | +"odd" if the day of the month for that timestamp is odd. |
| 7 | +"even" if the day of the month for that timestamp is even. |
| 8 | +For example, given 1769472000000, a timestamp for January 27th, 2026, return "odd" because the day number (27) is an odd number. |
| 9 | +""" |
| 10 | + |
| 11 | +import unittest |
| 12 | + |
| 13 | + |
| 14 | +class OddOrEvenDayTest(unittest.TestCase): |
| 15 | + |
| 16 | + def test1(self): |
| 17 | + self.assertEqual(odd_or_even_day(1769472000000), "odd") |
| 18 | + |
| 19 | + def test2(self): |
| 20 | + self.assertEqual(odd_or_even_day(1769444440000), "even") |
| 21 | + |
| 22 | + def test3(self): |
| 23 | + self.assertEqual(odd_or_even_day(6739456780000), "odd") |
| 24 | + |
| 25 | + def test4(self): |
| 26 | + self.assertEqual(odd_or_even_day(1), "odd") |
| 27 | + |
| 28 | + def test5(self): |
| 29 | + self.assertEqual(odd_or_even_day(86400000), "even") |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +from datetime import datetime |
| 36 | +def odd_or_even_day(timestamp): |
| 37 | + |
| 38 | + seconds = timestamp / 1000.0 |
| 39 | + date_obj = datetime.fromtimestamp(seconds) |
| 40 | + |
| 41 | + if date_obj.day % 2 == 0: |
| 42 | + return "even" |
| 43 | + else: |
| 44 | + return "odd" |
| 45 | + |
| 46 | +""" |
| 47 | +
|
| 48 | +1. Timezone awareness |
| 49 | +=> datetime.fromtimestamp() uses the localtimezon of the system. |
| 50 | +-> if you want consistent results regradless of environment, use datetime,utcfromtimestamp() |
| 51 | +
|
| 52 | +-> otherwise your function may return different results depending on where it runs. |
| 53 | +""" |
| 54 | + |
| 55 | +def odd_or_even_day(timestamp): |
| 56 | + |
| 57 | + dt = datetime.utcfromtimestamp(timestamp / 1000) |
| 58 | + |
| 59 | + day = dt.day |
| 60 | + |
| 61 | + return "odd" if day % 2 else "even" |
| 62 | + |
| 63 | +""" |
| 64 | +=> Use UTC consistently to avoid timezone shifts. |
| 65 | +-> datetime.utcfromtimestamp() in Python |
| 66 | +-> Parity check is just day % 2 |
| 67 | +""" |
| 68 | +def odd_or_even_day(timestamp): |
| 69 | + |
| 70 | + return "even" if datetime.utcfromtimestamp(timestamp / 1000).day%2 == 0 else "odd" |
| 71 | + |
| 72 | + |
| 73 | +odd_or_even_day = lambda ts: "even" if datetime.utcfromtimestamp(ts / 1000).day % 2==0 else "odd" |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + |
| 79 | + unittest.main() |
| 80 | + |
| 81 | + |
0 commit comments