Extract Day of Year and Julian Day from a String Date

Extract day of year and Julian day from a string date

First, you can convert it to a datetime.datetime object like this:

>>> import datetime
>>> fmt = '%Y.%m.%d'
>>> s = '2012.11.07'
>>> dt = datetime.datetime.strptime(s, fmt)
>>> dt
datetime.datetime(2012, 11, 7, 0, 0)

Then you can use the methods on datetime to get what you want… except that datetime doesn't have the function you want directly, so you need to convert to a time tuple

>>> tt = dt.timetuple()
>>> tt.tm_yday
312

The term "Julian day" has a few different meanings. If you're looking for 2012312, you have to do that indirectly, e.g., one of the following.

>>> int('%d%03d' % (tt.tm_year, tt.tm_yday))
2012312
>>> tt.tm_year * 1000 + tt.tm_yday
2012312

If you're looking for a different meaning, you should be able to figure it out from here. For example, if you want the "days since 1 Jan 4713 BC" meaning, and you have a formula that requires Gregorian year and day in year, you've got those two values above to plug in. (If you have a formula that takes Gregorian year, month, and day, you don't even need the timetuple step.) If you can't work out where to go from there, ask for further details.

If you don't have a formula—and maybe even if you already do—your best bet is probably to look around PyPI and ActiveState for pre-existing modules. For example, a quick search turned up something called jdcal. I'd never seen it before, but a quick pip install jdcal and a brief skim of the readme, and I was able to do this:

>>> sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))
2456238.5

That's the same result that the USN Julian date converter gave me.

If you want integral Julian day, instead of fractional Julian date, you have to decide which direction you want to round—toward 0, toward negative infinity, rounding noon up to the next day, rounding noon toward even days, etc. (Note that Julian date is defined as starting since noon on 1 Jan 4713BC, so half of 7 Nov 2012 is 2456238, the other half is 2456239, and only you know which one of those you want…) For example, to round toward 0:

>>> int(sum(jdcal.gcal2jd(dt.year, dt.month, dt.day)))
2456238

Extract Month From Julian day and year in python

Unless I am missing something, I think all you need is:

>>> import datetime
>>> s = '95365'
>>> datetime.datetime.strptime(s, '%y%j').month
12
>>> datetime.datetime.strptime(s, '%y%j').day
31
>>> datetime.datetime.strptime(s, '%y%j').year
1995

How to convert a D M Y HH:MM:SS string in Java to Julian Date?

java.time

Sure, Java has got a parser for date and time built-in, the DateTimeFormatter class (named so because it can also format date and time back to strings). And a number of classes that can utilize it for producing objects of themselves. In your case you need the LocalDateTime class. A LocalDateTime is a date and time of day without time zone or offset from UTC, so appropriate for holding the data from your string.

This formatter s good for your string:

private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("d MMM uuuu HH:mm:ss.SSS", Locale.ENGLISH);

Edit: You wrote in a comment:

Plugging in Jan 7 2010 hour 23 into this calculator:
aavso.org/jd-calculator gives
back 2455204.45833. Would this be the exact Julian Date? I believe
your solution was giving the Day instead of Date decimal value

Yes, that’s exactly true. The modified code to get the julian date including the fraction is:

    String source = "7 Jan 2010 23:00:00.000";

LocalDateTime ldt = LocalDateTime.parse(source, FORMATTER);
// Subtract half a day to compensate for the
// fact that the Julian day begins at noon
LocalDateTime dateToUseForJulianDay = ldt.minusHours(12);
long julianDayNumber = dateToUseForJulianDay.getLong(JulianFields.JULIAN_DAY);
double juianDateFraction = (double) dateToUseForJulianDay.getLong(ChronoField.NANO_OF_DAY)
/ (double) Duration.ofDays(1).toNanos();
double julianDate = julianDayNumber + juianDateFraction;

System.out.println("Julian date: " + julianDate);

And the output is in this example:

Julian date: 2455204.4583333335

It agrees very nicely with thee result you quote from the online calculator.

The Julian day number is the day number since January 1, 4713 BC. The Julian day starts at noon, which Java does not take into account, so as a hack I have subtracted 12 hours to compensate and get the correct day for all times of day. Since the getLong() method only gets the Julian day number as a whole number, I need to find the fraction separately. It’s a matter of dividing the nanosecond of the day by the total number of nanoseconds in a day. From the original date and time we would have needed the number of nanos since 12 noon; but since I have already subtracted 12 hours, the nanosecond of the day, since 0:00 midnight, is the number we need.

Further link: Julian day on Wikipedia

How to convert Julian date to standard date?

The .strptime() method supports the day of year format:

>>> import datetime
>>>
>>> datetime.datetime.strptime('16234', '%y%j').date()
datetime.date(2016, 8, 21)

And then you can use strftime() to reformat the date

>>> date = datetime.date(2016, 8, 21)
>>> date.strftime('%d/%m/%Y')
'21/08/2016'

YYYY-MM-DD date to Julian day in python

You can use strftime, check http://strftime.org/:

df = pd.DataFrame({'date': pd.date_range('2016-03-28', periods=5)})
print (df)
date
0 2016-03-28
1 2016-03-29
2 2016-03-30
3 2016-03-31
4 2016-04-01

df['newFormat'] = df['date'].dt.strftime('%y%j')
print (df)
date newFormat
0 2016-03-28 16088
1 2016-03-29 16089
2 2016-03-30 16090
3 2016-03-31 16091
4 2016-04-01 16092

Convert calendar date to julian date - python

You can use strftime for this (see this for a description of directives to use):

jul = df.strftime('%j')
>>> jul
'219'

Calculating julian date in python

Here you go - a pure python solution with datetime and math library.

This is based on the the Navy's Astronomical Equation found here and verified with their own calculator: http://aa.usno.navy.mil/faq/docs/JD_Formula.php

import datetime
import math

def get_julian_datetime(date):
"""
Convert a datetime object into julian float.
Args:
date: datetime-object of date in question

Returns: float - Julian calculated datetime.
Raises:
TypeError : Incorrect parameter type
ValueError: Date out of range of equation
"""

# Ensure correct format
if not isinstance(date, datetime.datetime):
raise TypeError('Invalid type for parameter "date" - expecting datetime')
elif date.year < 1801 or date.year > 2099:
raise ValueError('Datetime must be between year 1801 and 2099')

# Perform the calculation
julian_datetime = 367 * date.year - int((7 * (date.year + int((date.month + 9) / 12.0))) / 4.0) + int(
(275 * date.month) / 9.0) + date.day + 1721013.5 + (
date.hour + date.minute / 60.0 + date.second / math.pow(60,
2)) / 24.0 - 0.5 * math.copysign(
1, 100 * date.year + date.month - 190002.5) + 0.5

return julian_datetime

Usage Example:

# Set the same example as the Naval site.
example_datetime = datetime.datetime(1877, 8, 11, 7, 30, 0)
print get_julian_datetime(example_datetime)

Convert date (year, month, day) to Julian Day Number and back to date

The problem is in the definition of Julian Day. Taken from the page you linked:

Following Herschel's lead astronomers adopted this system and took noon GMT -4712-01-01 JC (January 1st, 4713 B.C.) as their zero point

So 2018-05-28 at 00.00 is 2458266.5, while 2018-05-28 at 12.00 is 2458267. If you watch your JulianNumber withut the Math.Ceiling in fact returns 2458266.5. Now, the page you linked (from which you took the second method, GregorianDate, uses only integers, so it works for dates that are at noon (12.00). So by rounding up (ceiling) the result of JulianNumber you are moving the date to the 12.00 hour, and making it "compatible" with the GregorianDate.

Possible solutions: use for JulianNumber the algorithm that is present in the same page and use only int everywhere (to show the fact that you are ignoring hours, minutes, seconds), or search for another algorithm for GregorianDate.



Related Topics



Leave a reply



Submit