Skip to content

Commit 4a19917

Browse files
mildsunriseByron
authored andcommitted
accept datetime instances as dates
There's no easy way to re-create a commit (i.e. for rewriting purposes), because dates must be formatted as strings, passed, then parsed back. This patch allows parse_date() to accept datetime instances, such as those produced by from_timestamp() above.
1 parent 6ef3775 commit 4a19917

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

Diff for: git/objects/util.py

+5
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ def parse_date(string_date):
135135
"""
136136
Parse the given date as one of the following
137137
138+
* aware datetime instance
138139
* Git internal format: timestamp offset
139140
* RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
140141
* ISO 8601 2005-04-07T22:13:13
@@ -144,6 +145,10 @@ def parse_date(string_date):
144145
:raise ValueError: If the format could not be understood
145146
:note: Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY.
146147
"""
148+
if isinstance(string_date, datetime) and string_date.tzinfo:
149+
offset = -int(string_date.utcoffset().total_seconds())
150+
return int(string_date.astimezone(utc).timestamp()), offset
151+
147152
# git time
148153
try:
149154
if string_date.count(' ') == 1 and string_date.rfind(':') == -1:

Diff for: test/test_util.py

+5
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,10 @@ def test_user_id(self):
174174
self.assertIn('@', get_user_id())
175175

176176
def test_parse_date(self):
177+
# parse_date(from_timestamp()) must return the tuple unchanged
178+
for timestamp, offset in (1522827734, -7200), (1522827734, 0), (1522827734, +3600):
179+
self.assertEqual(parse_date(from_timestamp(timestamp, offset)), (timestamp, offset))
180+
177181
# test all supported formats
178182
def assert_rval(rval, veri_time, offset=0):
179183
self.assertEqual(len(rval), 2)
@@ -200,6 +204,7 @@ def assert_rval(rval, veri_time, offset=0):
200204
# END for each date type
201205

202206
# and failure
207+
self.assertRaises(ValueError, parse_date, datetime.now()) # non-aware datetime
203208
self.assertRaises(ValueError, parse_date, 'invalid format')
204209
self.assertRaises(ValueError, parse_date, '123456789 -02000')
205210
self.assertRaises(ValueError, parse_date, ' 123456789 -0200')

0 commit comments

Comments
 (0)