Skip to content

Commit 3b7bdaf

Browse files
committed
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 3b7bdaf

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

git/objects/util.py

Lines changed: 5 additions & 0 deletions
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.timestamp()), offset
151+
147152
# git time
148153
try:
149154
if string_date.count(' ') == 1 and string_date.rfind(':') == -1:

test/test_util.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import tempfile
99
import time
1010
from unittest import skipIf
11-
from datetime import datetime
11+
from datetime import datetime, timezone, timedelta
1212

1313
import ddt
1414

@@ -188,18 +188,22 @@ def assert_rval(rval, veri_time, offset=0):
188188
self.assertEqual(utctz_to_altz(verify_utctz(utctz)), offset)
189189
# END assert rval utility
190190

191+
UTC_PLUS_TWO = timezone(timedelta(seconds=7200))
192+
dt = (datetime.fromtimestamp(1112911991, UTC_PLUS_TWO), -7200)
193+
191194
rfc = ("Thu, 07 Apr 2005 22:13:11 +0000", 0)
192195
iso = ("2005-04-07T22:13:11 -0200", 7200)
193196
iso2 = ("2005-04-07 22:13:11 +0400", -14400)
194197
iso3 = ("2005.04.07 22:13:11 -0000", 0)
195198
alt = ("04/07/2005 22:13:11", 0)
196199
alt2 = ("07.04.2005 22:13:11", 0)
197200
veri_time_utc = 1112911991 # the time this represents, in time since epoch, UTC
198-
for date, offset in (rfc, iso, iso2, iso3, alt, alt2):
201+
for date, offset in (dt, rfc, iso, iso2, iso3, alt, alt2):
199202
assert_rval(parse_date(date), veri_time_utc, offset)
200203
# END for each date type
201204

202205
# and failure
206+
self.assertRaises(ValueError, parse_date, datetime.now()) # non-aware datetime
203207
self.assertRaises(ValueError, parse_date, 'invalid format')
204208
self.assertRaises(ValueError, parse_date, '123456789 -02000')
205209
self.assertRaises(ValueError, parse_date, ' 123456789 -0200')

0 commit comments

Comments
 (0)