Skip to content

Instantly share code, notes, and snippets.

@peter216
Last active December 21, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter216/6361201 to your computer and use it in GitHub Desktop.
Save peter216/6361201 to your computer and use it in GitHub Desktop.
Converting Excel dates to UTC Epoch and back
# The key thing to notice here is that Excel dates are in seconds since
# December 30, 1899, expressed in days.
#!/env/python
from datetime import datetime, timedelta, timezone
def epoch2excel(epoch, tz=None):
if tz is None:
tz = timezone.utc
dtepoch = datetime.fromtimestamp(epoch, tz)
temp = datetime(1899, 12, 30, tzinfo=timezone.utc)
delta = dtepoch - temp
return float(delta.days) + (float(delta.seconds) / 86400)
def excel2epoch(exceldate, tz=None):
if tz is None:
tz = timezone.utc
temp = datetime(1899, 12, 30, tzinfo=tz)
exceldate = float(exceldate)
days = int(exceldate)
seconds = (exceldate - days) * 86400
date = temp + timedelta(days=days, seconds=seconds)
epoch = datetime(1970,1,1, tzinfo=timezone.utc)
return (date - epoch).total_seconds()
# # Unix
# $ date +%s
# 1377652599
#
# epoch = 1377652599
# exceldate = epoch2excel(epoch)
# print(exceldate)
#
# 41514.0532292
#
# backto_epoch = excel2epoch(exceldate)
# print(backto_epoch)
#
# 1377652599.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment