Fixing timestamps on existing git commits

Fixing timestamps on existing git commits

Need to move all of your git commits a few hours to the future or the past, for example to fix a timezone issue? You've come to the right place.

This is something I expected would be easy to find online, but wasn't. So I'm leaving it here, in case someone else is googling for it as well.

First, you need to install git-filter-repo, a great tool for manipulating git repositories. This is a destructive action, so do it at your own risk. The tool will warn you, though.

To move all commits 3 hours ahead, run this:

git filter-repo --commit-callback 'commit.author_date = (str((datetime.utcfromtimestamp(int(commit.author_date.decode("utf-8")[:10])) + timedelta(hours = 3)).timestamp())[:-2] + \' +0100\').encode()'

Is it pretty? No. I've been trying to copypaste something that would fix the issue, not trying to come up with the best way to solve it. If you have a better one, do send it to me.

It works like this:

  • --commit-callback lets you specify a piece of python code to run for each commit in the repo
  • the timestamp is stored in the author_date of the commit object
  • its format is "1626812273 + 0100" - i.e. the Unix timestamp + timezone. (Never saw this one before.) And it is represented as bytes, not a string.
  • So the piece of code takes the timestamp, converts it to a datetime, adds 3 hours, then sticks it all together into a bytestring again.

Change the number of 'hours' as you need, and maybe change the hard-coded timezone if yours is different. HTH.