将Python的datetime转换为自定义的纪元时间。

huangapple go评论60阅读模式
英文:

Convert python datetime to custom epoch time

问题

我需要将日期时间转换为一种格式,其中值的整数部分(小数点左侧)表示自1899年12月30日以来的天数。小数部分(小数点右侧)表示时间占一天的分数。例如,1900年1月1日中午是2.5,其中2表示自1899年12月30日以来的2天,0.5表示中午是一天的一半。1900年2月1日下午3点是33.625。

我将日期字符串转换为日期时间,然后使用strptime将其转换为时期时间。

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

但它返回自1900年1月1日以来的秒数,而我需要小数点左侧为天数,小数点右侧为一天的时间分数。

英文:

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.

答案1

得分: 1

以下是翻译好的代码部分:

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

或者简化版本

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)
英文:

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)

huangapple
  • 本文由 发表于 2023年5月21日 05:33:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定