Majoris
Majoris

Reputation: 3189

Julian day number to local date-time in python

Trying to convert Julian day number to local date-time python. How to accomplish this?

juliandate = 2474706.5316357147
print (datetime.strptime(juliandate, '%Y%j').date())

    print (datetime.strptime(juliandate, '%Y%j').date())
TypeError: strptime() argument 1 must be str, not float

Upvotes: 2

Views: 2829

Answers (1)

FObersteiner
FObersteiner

Reputation: 25594

A convenient way could be using pandas' to_datetime with appropriate origin and unit, e.g.

import pandas as pd

juliandate = 2459168.298
t = pd.to_datetime(juliandate, origin='julian', unit='D')
print(t)
# 2020-11-14 19:09:07.200000

# to python datetime:
# t.to_pydatetime().replace(tzinfo=timezone.utc)

Or if you like to stick to the standard lib, you could make use of timedelta. The epoch of julian, 12h Jan 1 4713 BC, is a bit far in the past, so it helps to introduce an offset for a more recent date, e.g.

from datetime import datetime, timedelta, timezone

dt_Offset = 2400000.500 # 1858-11-17
dt = datetime(1858, 11, 17, tzinfo=timezone.utc) + timedelta(juliandate-dt_Offset)
print(dt)
# 2020-11-14 19:09:07.199996+00:00

see also: julian day on wikipedia

Note that both results are in UTC. If you want convert to a certain time zone, have a look at astimezone, e.g.

from zoneinfo import ZoneInfo
print(dt.astimezone(ZoneInfo('US/Eastern')))
# 2020-11-14 14:09:07.199996-05:00

# or my machine's local time (CET):
print(dt.astimezone())
# 2020-11-14 20:09:07.199996+01:00

Upvotes: 5

Related Questions