Skip to content

Accept datetime instances as dates #1050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,5 @@ Contributors are:
-Harmon <harmon.public _at_ gmail.com>
-Liam Beguin <liambeguin _at_ gmail.com>
-Ram Rachum <ram _at_ rachum.com>
-Alba Mendez <me _at_ alba.sh>
Portions derived from other open source works and are clearly marked.
5 changes: 5 additions & 0 deletions git/objects/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ def parse_date(string_date):
"""
Parse the given date as one of the following

* aware datetime instance
* Git internal format: timestamp offset
* RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
* ISO 8601 2005-04-07T22:13:13
Expand All @@ -144,6 +145,10 @@ def parse_date(string_date):
:raise ValueError: If the format could not be understood
:note: Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY.
"""
if isinstance(string_date, datetime) and string_date.tzinfo:
offset = -int(string_date.utcoffset().total_seconds())
return int(string_date.astimezone(utc).timestamp()), offset

# git time
try:
if string_date.count(' ') == 1 and string_date.rfind(':') == -1:
Expand Down
5 changes: 5 additions & 0 deletions test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ def test_user_id(self):
self.assertIn('@', get_user_id())

def test_parse_date(self):
# parse_date(from_timestamp()) must return the tuple unchanged
for timestamp, offset in (1522827734, -7200), (1522827734, 0), (1522827734, +3600):
self.assertEqual(parse_date(from_timestamp(timestamp, offset)), (timestamp, offset))

# test all supported formats
def assert_rval(rval, veri_time, offset=0):
self.assertEqual(len(rval), 2)
Expand All @@ -200,6 +204,7 @@ def assert_rval(rval, veri_time, offset=0):
# END for each date type

# and failure
self.assertRaises(ValueError, parse_date, datetime.now()) # non-aware datetime
self.assertRaises(ValueError, parse_date, 'invalid format')
self.assertRaises(ValueError, parse_date, '123456789 -02000')
self.assertRaises(ValueError, parse_date, ' 123456789 -0200')
Expand Down