Home > Net >  How to convert hours from a starting date to year, month, and day
How to convert hours from a starting date to year, month, and day

Time:02-03

The data below are hours starting from 1800:00:00.0

I am trying to convert them to day, month, and year starting from the above date.

1.52887e 06
1.52959e 06
1.53034e 06
1.53108e 06
1.5318e 06
1.53254e 06
1.53326e 06
1.53401e 06
1.53475e 06
1.53542e 06
1.53617e 06
1.53689e 06
1.53763e 06

I want to convert them to day, month, and year from that starting date.

thanks

CodePudding user response:

Here is one approach using datetime:

from datetime import datetime, timedelta

start_date = datetime(year=1800, month=1, day=1, hour=0, minute=0, second=0)
formatted_dates =[]

for hour in hours:
    date = start_date   timedelta(hours=hour)
    formatted_dates.append("{0}-{1}-{2}".format(date.day, date.month, date.year))
print(formatted_dates)

['31-5-1974', '30-6-1974', '1-8-1974', '1-9-1974', '1-10-1974', '31-10-1974', '30-11-1974', '1-1-1975', '31-1-1975', '28-2-1975', '1-4-1975', '1-5-1975', '31-5-1975']

CodePudding user response:

Using the datetime module, the timedelta method is used to add the hours to the starting date to get the converted dates.

import datetime

start_date = datetime.datetime(1800, 1, 1)
dates = [start_date   datetime.timedelta(hours=hour) for hour in hours]

for date in dates:
    print(date.strftime("%d %b %Y %H:%M:%S"))

Output:

31 May 1974 22:00:00
30 Jun 1974 22:00:00
01 Aug 1974 04:00:00
01 Sep 1974 00:00:00
01 Oct 1974 00:00:00
31 Oct 1974 20:00:00
30 Nov 1974 20:00:00
01 Jan 1975 02:00:00
31 Jan 1975 22:00:00
28 Feb 1975 20:00:00
01 Apr 1975 02:00:00
01 May 1975 02:00:00
31 May 1975 22:00:00
  • Related