**Advertisement**

# dateToTimeStamp function work on yyyy-mm-dd # This function feature is to convert a date string in the format of yyyy-mm-dd or yyyy/mm/dd to a Unix timestamp. # To read the entire tutorial please follow kevinhng86 blog @ http://kevinhng86.iblog.website . # There are other versions of this timestamp converter available on my website. # Without this function you can use the Python's built-in function. # This function will work from the year 50 to 5500 due to how much a 64 bits long integer can hold. # Python's built-in library code: # import time # import datetime # myDate = "2000-2-28" # timestamp = time.mktime(datetime.datetime.strptime(myDate, "%Y-%m-%d").timetuple()) # print timestamp # # Python library can't convert time value that is below the year 1750. def dateToTimeStamp(value): import re # This is the output value out = 0 # An array for splitting input. datearray = [] # Without an input value, the script will end. if value is None or len(value) < 1: raise Exception("There is not an input value") # First, check for the format of yyyy-mm-dd if re.match("^\d{4}-{1}\d{1,2}-{1}\d{1,2}$", value): # Split the digits into chunks and store into an array. datearray = value.split("-") # Second, evaluate date in the format of yyyy/mm/dd elif re.match("^\d{4}\/{1}\d{1,2}\/{1}\d{1,2}$", value): datearray = value.split("/") # If the input value does not match the previous date format, the program will exit with an error. else: raise Exception("Incorrect format") # Convert the date values that stored inside the datearray into an integer value that corresponding to year, month and date. inyyyy = int(datearray[0]) inmm = int(datearray[1]) indd = int(datearray[2]) # Evaluate if the year is a leap year. isLeap = 1 if (inyyyy % 4) == 0 else 0 # Evaluate if the year is a century leap year. isCenturyLeap = 1 if (inyyyy % 100) == 0 else 0 # Evaluate if the year is a quad century leap year. isQuadCenturyLeap = 1 if (inyyyy % 400) == 0 else 0 # Month value can't be greater than 12. if(inmm > 12): raise Exception("Month cannot be greater than 12.") # Date value can't be larger than 31. if(indd > 31): raise Exception("Day cannot be great than 31.") # Date value can't be larger than 29 if the month is February if (inmm == 2 and indd > 29): raise Exception("February can't have more than 29 days") # For the month of April, June, September and November, the date value can't be greater than 30. if ((inmm == 4 and indd > 30) or (inmm == 6 and indd > 30) or (inmm == 9 and indd > 30) or (inmm == 11 and indd > 30)): raise Exception("April, June, September and November can't have more than 30 days") # Year, date or month's values can't be less than one. if (inmm < 1 or indd < 1 or inyyyy < 1): raise Exception("Month date and years input can't be less than 1") # The maximum support for this timestamp converter is a 64 bits long integer. Therefore, I safety net the below year to the year 50. if (inyyyy < 50): raise Exception("Memory doesn't allow us to convert year below 50") # The maximum support for this timestamp converter is a 64 bits long integer. Therefore I safety net the above year to the year 5500. if (inyyyy > 5500): raise Exception("Memory doesn't allow us to convert year above 5500") # If this is not a leap year then February can't have more than 28 days. if (isLeap != 1 and inmm == 2 and indd > 28): raise Exception("This is not a leap year, you can't have 29 days in Feburary") # If this is a century leap year but is not a quad centuary leap year then February can't have more than 28 days. if (inmm == 2 and isCenturyLeap == 1 and isQuadCenturyLeap != 1 and indd > 28): raise Exception("This February can't have 29 days. Although it is a leap year, leap year is skipped on years that are divisible 100 years but will not skip if the year is divisible by 400") # This array store the amount days that each month have. We count February as a constant of 28 days because we will modify our equation to match the leap year value. dateinmonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Variable for storing how many leap days occur since input year to 1972 or to 1968 leapv = 0 # This is the index we would use to get the days from the dateinmonth array. aridx2 = inmm - 1 # Variable for storing the total date since input year to 1972 or 1968. totaldate = 0 # Variable for storing the year from. yeardate = 0 # Variable for storing how many days left in the current year of the input date. dateleftinyear = 0 # Variable for storing how days left in the current month of the input value. dateleftinmonth = 0 # What is a timestamp? A timestamp is a number string that contains a time value with the format of how many second since the 0:0:0 time of January 1, 1970. # Timestamps are actually measured in milliseconds, However, for this tutorial, we only use the second for measurement. # Negative timestamp is how far a time is below 1970. For instance, any date in 1969 and below will generate a negative timestamp. # Positive timestamp is how far a time is above 1970. For instance, any date in 1970 and above will generate a positive timestamp. 1970 1 1 in this tutorial will generate a 0 timestamp. # The first challenge we meet is the leap year. # Timestamp takes into account leap years, century leaps and quad century leaps. # What does leap years mean? # We get the 29th day in February if the year is divisible by four. We don't get the 29th day if the year is divisible by 100 but is not divisible by 400. # The method I prefer to use for calculating leap is if we are above 1970, we will use the closet below leap year. Which would be the year 1968 for calculating leap year value. # This is the fact that we only need to round down our number after we subtract the year value to 1968 then divide by four. # If we use 1970 every time we hit a decimal .5 or .75 we have to round up. # My formula for calculating time values that are above the 0:0:0 time of January 1st, 1970 is as follow: # Since we use leap to calculate to 1968, we will calculate to the 1st day of 1968 and then subtract off the result value a value of two 365 days years. # y = (input year value - 1968) * 365 # d = date from the beginning of year = 365 - ((total date in input month - input date) + (How many day left in the year since one month after the input month). # l = How many times leap year has occurred since 1968. Take input year - 1968 / 4. The whole number here is what we want not the decimal. If the value contained a decimal point, leap year had not happened yet for the decimal part of the value. # c = How many times century leap has occurred since 1968. Input year - 1968 / 100. The whole number here is what we want and not the decimal. # q = How many times quad century leap has occurred since 1968. Input year - 1968 / 400. The whole number here is what we want and not the decimal. # totaldate = y - d + l - c + q ; # timestamp = (totaldate * 86400) - 63158400 // 86400 is how many seconds that is in a day. and 63158400 is the amount of second that contains within two years that is 365 days each. # Since we are calculating to 1968 we have to subtract the amount of second in two years from the result value. # For the purpose of this tutorial I divide the code into what happen if the time value is above the 0:0:0 time of 1970 and what happen if it is below. # It is possible to combine the equation and modify the equation as desired. if inyyyy >= 1970: leapv = int((inyyyy - 1968) / 4) centuryleapv = int((inyyyy - 2000) / 100) quadcenturyleapv = int((inyyyy - 2000) / 400) length = len(dateinmonth) # Get how many date left in a the year since after the input month. dateleftinmonth = dateinmonth[aridx2] - indd # Get how many days occurred since the begining of year to input date by subtracting 365 to (dateleftinmonth + dateleftinyear) for i in range(inmm, length): dateleftinyear = dateleftinyear + dateinmonth[i] datefrombeginingofyear = 365 - (dateleftinmonth + dateleftinyear) # The real challenge we have for calculating leap is. # On the year that it is a leap year, we do not have the extra day until we have passed the 29th of February. # Hence, although in a leap year, if we have not passed the 29th day, we can't add leap values to our equation. # However, the automatic formula has already taken into account the values for leap year. # Therefore those values, have to be subtract off if we has not passed the 29 day of Feburary. # Each if loop below is associate with a type of leap calculation. if (isLeap == 1 and inmm < 3): leapv = leapv - 1 if (inmm < 2) or (inmm == 2 and indd <= 29) else leapv if (isCenturyLeap == 1 and inmm < 3): centuryleapv = centuryleapv - 1 if (inmm < 2) or (inmm == 2 and indd <= 29) else centuryleapv if (isQuadCenturyLeap == 1 and inmm < 3): quadcenturyleapv = quadcenturyleapv - 1 if (inmm < 2) or (inmm == 2 and indd <= 29) else quadcenturyleapv # After evaluate and obtains all necessary value for the formula, we would calculate the result. yeardate = (inyyyy - 1968) * 365 totaldate = yeardate + datefrombeginingofyear + leapv - centuryleapv + quadcenturyleapv out = (totaldate * 86400) - 63158400 else: # My formula for calculating time values that are before the 0:0: time of January 1st, 1970 is as follow: # The method I prefer to use for calculating leap values is, if we are below the year of 1970, we will use the closet above leap year, which would be the year 1972 for leap values calculation. # Since we use the year 1972 for calculating leap values, we will calculate the second value to the 1st day of 1972, then we subtract two 365 days years from the equation. # y = (input year value - 1972 + 1) * 365 # We will have a negative value of how far we are away from 1972, but we have to add one year here. # # This is because 1971 can be considered to be one year away from 1972. # # However it is not. We are still within the time frame of 365 days away but not really one year away from 1972. # Because we are calculating how far we are below. # We simply just calculating how many days left in the year since the input date value. # The previous procedure will let us know how far we are away from the end of the year. # d = day left in the month = total day in input month - input date. # e = day left in the year = total day left in the year after the input month. # # We want all the number below to be positive now. # l = How many times leap year has occurred since 1972. 1972 - input year / 4. The whole number here is what we want and not the decimal value. The decimal values are leap year that has not occurred. # c = How many times century leap has occurred since 1972. 1972 - input year / 100. The whole number here is what we want and not the decimal value. # q = How many times century leap occur since 1972. 1972 - input year / 400. The whole number here is what we want and not the decimal value. # The number now are in positive so that mean the further negative the further it is away. # totaldate = y - d - e - l + c - q # timestamp = (totaldate * 86400) + 63158400 - 172800 # 86400 is how many seconds that is in a day. and 63158400 is the amount of second that contained within a time frame of two 365 days years. # # Since we calculate to 1972 we have to give back this value. # # We have to also subtract two days from the equation which would be 172800 seconds. # # In this formula, if we are on the 31st day of December 1969 to 1970 1 1. # # We will not have any day left in the month or any day left in the year. # # Hence that is a 0 value, but in true reality, we are one day away if we are counting from the zero hour. # # Thus we have to subtract one day from the equation. leapv = int((1972 - inyyyy) / 4) centuryleapv = int((2000 - inyyyy) / 100) quadcenturyleapv = int((2000 - inyyyy) / 400) length = len(dateinmonth) # There is a difference when we are evaluating leap calculation for a time value that is before the time 0:0:0 of January 1st, 1970. # Leap values will not be added to the equation unless we have passed the first day of March. if (isLeap == 1 and inmm > 2): leapv = leapv - 1 if ((inmm > 2) or (inmm == 3 and indd >= 1)) else leapv if (isCenturyLeap == 1 and inmm > 1): centuryleapv = centuryleapv - 1 if ((inmm > 2) or (inmm == 3 and indd >= 1)) else centuryleapv if (isQuadCenturyLeap == 1 and inmm > 1): quadcenturyleapv = quadcenturyleapv - 1 if ((inmm > 2) or (inmm == 3 and indd >= 1)) else quadcenturyleapv dateleftinmonth = dateinmonth[aridx2] - indd for i in range(inmm, length): dateleftinyear = dateleftinyear + dateinmonth[i] yeardate = (inyyyy - 1972 + 1) * 365 totaldate = yeardate - dateleftinmonth - dateleftinyear - leapv + centuryleapv - quadcenturyleapv out = (totaldate * 86400) + 63158400 - 172800 return out print(dateToTimeStamp("5000-3-1"))

**Advertisement**