Skip to content

Instantly share code, notes, and snippets.

@TMcManus
Created June 29, 2013 18:37
Show Gist options
  • Save TMcManus/5892177 to your computer and use it in GitHub Desktop.
Save TMcManus/5892177 to your computer and use it in GitHub Desktop.
Sometimes you just need to create a timestamp in Python with no dependencies. This function creates timestamps without requiring any imports.
def pure_python_timestamp(year, month, day, hour, minute, seconds):
"""
Sometimes you just need to create a timestamp in Python with no dependencies.
This function creates timestamps without requiring any imports.
Note: This function doesn't fully take into account the century rules for leap years.
>>> pure_python_timestamp('1994','11','19', '22', '01', '22')
785282482
>>> pure_python_timestamp('2013','07','03', '08', '14', '15')
1372839255
>>> pure_python_timestamp('2020','02','29', '06', '18', '37')
1582957117
>>> pure_python_timestamp('2020','05','21', '07', '02', '01')
1590044521
>>> pure_python_timestamp('2031','12','17', '23', '56', '47')
1955318207
"""
days_before_month = {
'01': 0, '02': 31, '03': 59, '04': 90, '05': 120, '06': 151,
'07': 181, '08': 212, '09': 243, '10': 273, '11': 304, '12': 334,
}
epoch_start = 1970
leap_year_after_epoch = 1972
# We're going to be using this a lot, so going to cast it early
year = int(year)
# Create the base timestamp with regular math
years_since_epoch = year - epoch_start
timestamp = (years_since_epoch * 31536000) \
+ (days_before_month[month] * 86400) \
+ (int(day) * 86400) \
+ (int(hour) * 3600) \
+ (int(minute) * 60) \
+ int(seconds)
# Some crazy logic to figure out if it's a leap year
if year % 400 == 0:
leap_year = True
elif year % 100 == 0:
leap_year = False
elif year % 4 == 0:
leap_year = True
else:
leap_year = False
# Some logic to account for the extra days from past leap years
if leap_year is False:
past_leap_years = ((year - leap_year_after_epoch) / 4) * 86400
else:
if int(month) < 3:
past_leap_years = ((year - leap_year_after_epoch) / 4) * 86400
past_leap_years = past_leap_years - 86400
else:
past_leap_years = ((year - leap_year_after_epoch) / 4) * 86400
# Add the days from past leap years to the timestamp
timestamp = timestamp + past_leap_years
return timestamp
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment