How To Convert Date To Timestamp Using Your Own Library - Python

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
Hello all,

I got this new tutorial I just wrote. This version is in Python, I have this in many version. Currently I'm writing this small function into Ruby, C# and C. I have it in PHP, Javascript, Python, Perl. If you like it and want to see it in other format. Check out my blog @ http://kevinhng86.iblog.website. This simple script will demonstrate to you, how to convert a Date string into timestamp without needing to use anyone else library. It is not that big of a source code mostly because I write the tutorial inside it.

Code:
# dateToTimeStamp function work on yyyy-mm-dd
# This function features is to convert a date string in the format of yyyy-mm-dd pr yyyy/mm/dd to a unix timestamp.
# To read the entire tutorial please follow kevinhng86 blog @ http://kevinhng86.iblog.website .
# This tutorial is for Python and this source code is for Python. 
# If you interest in learning time stamp converting in other programming language, look for it's on my website.
# Without this function you can use the built in Python function library. 
# This function will work from the year 50 to 5500 due to memory allocation problem.
# Python 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 draw back is it can't go below the year 1750


def dateToTimeStamp(value):

     import re
     out = 0         # This is the output value
     datearray = []  # This array is use to split the input
    
     if value is None or len(value) < 1:    # No input value the script will die.
         raise Exception("There is not an input value")
     if re.match("^\d{4}-{1}\d{1,2}-{1}\d{1,2}$", value):     # This check for 4 number for years plus a dash, 1 or 2 number for months plus a dash and 1 or 2 number for day plus a dash'''
         datearray = value.split("-")                         # Split the number into an array.
     elif re.match("^\d{4}\/{1}\d{1,2}\/{1}\d{1,2}$", value): # This check for 4 number for years plus a /, 1 or 2 number for months plus a / and 1 or 2 number for day plus a /
         datearray = value.split("/")                         # Split the number into an array.
     else:
         raise Exception("Incorrect format") # If none of the above value match the script will exit with error
     
 
     # Convert the string that store in the array into interger
     inyyyy = int(datearray[0]) 
     inmm = int(datearray[1])
     indd = int(datearray[2])
    
     # Check to see if the input year is leap year, century leap year or quadcentury leap year.
     # If any of the condition is true the variable will store a one else it will store a 0.
     isLeap = 1 if (inyyyy % 4) == 0 else 0
     isCenturyLeap = 1 if (inyyyy % 100) == 0 else 0
     isQuadCenturyLeap = 1 if (inyyyy % 400 ) == 0 else 0
 
     # Can't have more than 12 months
     if(inmm > 12):
         raise Exception("Month cannot be greater than 12.")
     # Can't have more than 31 days.
     if(indd > 31):
         raise Exception("Day cannot be great than 31.")
     
     
     # Can't have more than 29 days in february
     if (inmm == 2 and indd > 29):
         raise Exception("February can't have more than 29 days")
         
     # In April, June, September and November we only have 30 days.
     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")
 
     # Nothing can be less than 1
     if (inmm < 1 or indd < 1 or inyyyy < 1):
         raise Exception("Month date and years input can't be less than 1")
 
     # Year can't be less than 50 due to memory allocation problem for storing one interger value
     if (inyyyy < 50):
         raise Exception("Memory doesn't allow us to convert year below 50")
 
     # Year can't be less more than 5500 due to memory allocation problem for storing one interger value
     if (inyyyy > 5500):
         raise Exception("Memory doesn't allow us to convert year above 5500")
     
     
     # If this is not a leap year than 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, we 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")
     

     # We set variable here in the event where the input value doesn't pass test. It won't consume much memory;
     dateinmonth = [31,28,31,30,31,30,31,31,30,31,30,31] # This is how many day in each month. We count february at 28 because we will modify our equation to match the leap year value.
     leapv = 0             # Variable for storing how many leap days occur since 
     aridx2 = inmm - 1     # This is the index we use to know which month we are on from the @dateinmonth array.
     totaldate = 0         # Variable for storing the total date since 1970 1 1
     yeardate = 0          # Variable for storing the year from  
     dateleftinyear = 0    # Variable for storing how many date left in the input value currentyear
     dateleftinmonth = 0   # Variable for storing how date left in the input value current month
     
     # So what is a timestamp. A timestamp is a number string that contain time value with the format of how many second since January 1, 1970.  
     # Timestamp actually measure in milisecond however for this tutorial we only use the second 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 leap year.
     # Timestamp take into account leap years, century leaps and quad century leaps.
     # What does leap years mean?
     # We get the 29 day in February if the year is divisble by four, we dont get the 29 day if the year is divisible by 100 but not 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 is 1968 to calculate leap. 
     # This is the fact that we only need to round down our number after we minus year to 1968 and 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 year above 1970 is follow: 
     # Since we use leap to calculate to 1968 we will calculate to the 1st day of 1968 and then minus of two 365 days year from the equation.
     # y = (input year value - 1968) * 365
     # d = date from the begining of year = 365 - ( (total date in input month - input date) + ( how many date left in the year 1 month after input month);
     # l = how many time leap year that divisble by 4 occur since 1968. Take input year - 1968 / 4 , the whole number here is what we want not the decimal. Since it is decimal it had not happen yet.
     # c = how many time century leap occur since 1968. Input year - 1968 / 100, the whole number here is what we want not the decimal. 
     # q = how many time century leap occur since 1968. Input year - 1968 / 400, the whole number here is what we want not the decimal. 
     # totaldate = y - d + l - c + q ;
     # timestamp = (totaldate * 86400) - 63158400   # 86400 is how many second in a day. and 63158400 is the second that contain within two years that is 365 days each.
     #                                              # Since we calculate to 1968 we have to give back this value.
     #
     # The formula for calculating the timestamp for if below 1970 will be put down below.
     # For the purpose of this tutorial I divide the code into what happen if the year is above 1970 and what happen if it is below.
     # Once you understand the concept it is possible to combine them and modify the equation.
     #
       
     if inyyyy >= 1970 :
        leapv = int( (inyyyy - 1968)/4 )                   # Get the whole interger for how many time leap year had occur since 1968.  
        centuryleapv = int( (inyyyy - 2000)  / 100 )       # Get the whole interger for how many time century leap year had occur since 1968. 
        quadcenturyleapv = int( (inyyyy - 2000) / 400 )    # Get the whole interger for how many time quad century leap year had occur since 1968.
        length = len(dateinmonth)
 
        dateleftinmonth = dateinmonth[aridx2] - indd       # Get how many date left in the current input month
 
 
        for i in range(inmm, length):
            dateleftinyear = dateleftinyear + dateinmonth[i]   # Get how many date left in a the year since after the input month. 
                                                              # Array index start at 0 therefore we do not need to add 1 to our indexer.
       
        datefrombeginingofyear = 365 - (dateleftinmonth + dateleftinyear) # Get the date from the begining of year until input date by minus 365 to (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 pass the 29 of february.
        # Hence although in a leap year if it does not pass the 29 we can't add leap to our equation.
        # However the automatic formula already took in account the leap year. Therefore those have to be minus off if it does not pass the 29 day of Feburary.
        # Each if loop below is associate with a 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 get all value we calculating. Assign the value to the out variable.
        yeardate = (inyyyy - 1968) * 365 
        totaldate = yeardate + datefrombeginingofyear + leapv - centuryleapv + quadcenturyleapv 
        out = (totaldate * 86400) - 63158400
       
     else:
 
     # My formula for calculating year below 1970 is follow: 
     # The method I prefer to use for calculating leap is if we are below 1970 we will use the closet above leap year, which is 1972 to calculate leap. 
     # Since we use leap to calculate to  we will calculate to the 1st day of 1968 and then minus of two 365 days year 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 here.
     #                                            # This is due to the fact that 1971 can be consider be one year away from 1972.
     #                                            # However it is not. We are still within the 365 day away but not really one year away.
     #   since now are calculating how far we are below. 
     #   We simply just calculating how many days left in the year since our input value.
     #   This will get us how far we are away from the end of the year.
     #  d = date left in month = total day in input month - input date.
     #  e = date left in year = total left in the year after the input month.
     #     
     #  We want all the number below to be positive now.    
     #  l = how many time leap year that divisble by 4 occur since 1968. 1972 - input year / 4 , the whole number here is what we want not the decimal. Since it is decimal it had not happen yet.
     #  c = how many time century leap occur since 1968. 1972 - input year / 100, the whole number here is what we want not the decimal. 
     #  q = how many time century leap occur since 1968. 1972 - input year / 400, the whole number here is what we want not the decimal. 
     #  The number now are in positive so that mean the further negative the further it is away and so forth.        
     #  totaldate = y - d - e - l + c - q ;
     #  timestamp = ($totaldate * 86400) + 63158400 - 172800; # 86400 is how many second in a day. and 63158400 is the second that contain within two years that is 365 days each. 
     #                                                        # Since we calculate to 1972 we have to give back this value.
     #                                                        # We have to minus two days to the equation which 172800 represent in second value.
     #                                                        # In this formula if we are on the 31 day of december 1969 to 1970 1 1.
     #                                                        # We will not have any day left in month or any day left in year.
     #                                                        # Hence that is 0, but really we are on days away if we count by 0 hours.
     #                                                        # Thus we have to minus of one day.
     #                                                        # The same principle apply when we borrow the 2 years to 1972
     #                                                          
     #
        leapv = int( (1972 - inyyyy)/4 )  
        centuryleapv = int( ( (2000 - inyyyy)  / 100) ) 
        quadcenturyleapv = int(  (2000 - inyyyy) / 400  ) 
        length = len(dateinmonth)
 
 
       # The check leap here is difference since we going further down.
       # Leap day will not be any further unless we pass march the first.
        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 output value.
    # Most the the explanation already explain above.
    # Stay tune for how to convert a timestamp back to date format without using a built in function.
     return out
     
     
     
print dateToTimeStamp("1200-2-29")
 
Newer Threads
Replies
6
Views
3,122
Replies
33
Views
13,534
Replies
5
Views
5,805
Replies
7
Views
11,675
Replies
6
Views
4,700
Latest Threads
Replies
1
Views
19
Replies
0
Views
171
Replies
1
Views
37
Replies
2
Views
80

Latest postsNew threads

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top