Reputation: 3577
I have a df like so:
ImageDate Year Month Day
20020506 2002 05 06
20030605 2003 06 05
20040201 2002 02 01
and I want to add a new column which converts the dates into julian dates. I am pretty sure I need the module datetime
to do this, but I looked through the docs and didn't find anything that was apparent to me on how to do this.
Upvotes: 1
Views: 5651
Reputation: 61
#Import python datetime library.
import datetime as dt
#Lets consider you want to convert the below date. You can have the date in any order like CCYY-MM-YY or MM-DD-CCYY or with different separator like CCYY/MM/YY.
GregDate = '2020-03-30'
# Specify the date and format within strptime in this case format is %Y-%m-%d (if your data was 2020/03/30' then use %Y/%m/%d) and specify the format you want to convert into in strftime, in this case it is %Y%j. This gives out Julian date in the form CCYYDDD, if you need only in YYDDD give the format as %y%j
Juldate = dt.datetime.strptime(GregDate, "%Y-%m-%d").strftime('%Y%j')
# Print your variable to display the result
print(Juldate)
2020090
Upvotes: 0
Reputation: 1918
The following is my python implementation of the original conversion algorithm published here:
def gregorian_to_julian(year, month, day):
i = int((month - 14) / 12)
jd = day - 32075
jd += int((1461 * (year + 4800 + i)) / 4)
jd += int((367 * (month - 2 - (12 * i))) / 12)
jd -= int((3 * int((year + 4900 + i) / 100)) / 4)
return jd
For example:
>>> gregorian_to_julian(1970, 1, 1)
2440588
alternatively, you can use the built-in date object to get the Julian date from Gregorian date by adding the Julian date of Gregorian absolute date 0 which is 1,721,425 to ordinal date as published here:
>>> from datetime import date
>>> date(1970, 1, 1).toordinal() + 1721425
2440588
The second solution is simpler and much faster.
Upvotes: 2
Reputation: 735
Go take a look at this library : https://pypi.python.org/pypi/jdcal
And do something like : `
from jdcal import gcal2jd, jd2gcal
gcal2jd(2000,1,1)'
Upvotes: 2