Convert python datetime to custom epoch time

Question:

I need to convert datetime to a format where the whole number portion of the value (left of the decimal) counts the days since December 30, 1899. The fractional portion (right of the decimal) counts the time as a fraction of one day. For example, January 1, 1900 at noon is 2.5, 2 because it’s 2 days after December 30, 1899, and 0.5 because noon is half a day. February 1, 1900 at 3 PM is 33.625.

I convert date in string to datetime with strptime and then convert it to epoch time with strptime.

datee = "03/11/2005, 23:12"
date = datetime.datetime.strptime(datee, "%d/%m/%Y, %H:%M")
epoch = date.timestamp()

But it return seconds from January 1, but i need days on the left side of the decimal and time as a fraction of one day on the right side of the decimal.

Asked By: voviz

||

Answers:

this should do what you want:

import datetime

def convert_to_custom_format(date_string):
    date_format = "%d/%m/%Y, %H:%M"
    date = datetime.datetime.strptime(date_string, date_format)
    base_date = datetime.datetime(1899, 12, 30)
    delta = date - base_date
    days = delta.days
    seconds_in_day = 24 * 60 * 60
    time_fraction = delta.seconds / seconds_in_day
    return days + time_fraction

or the short version:

def convert_to_custom_format(date_string):
    date_format = "%d/%m/%Y, %H:%M"
    base_date = datetime.datetime(1899, 12, 30)
    return (datetime.datetime.strptime(date_string, date_format) - base_date).total_seconds() / (24 * 60 * 60)
Answered By: Lino
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.