How to convert Decimal to GIS coordinates in SQL? - azure-sqldw

I have GIS coordinates stored in one of our systems as Decimals. However, I would like to display them as Degrees:mins:secs. I tried Googling but couldn't find anything for SQL. Could someone please help me?
CREATE TABLE gis
(
latitude DECIMAL(13, 10)
);
INSERT INTO gis
SELECT -95.8833333000
UNION ALL
SELECT 32.5530555550
UNION ALL
SELECT -163.3000000000
Thanks!

I was able to do this based on this blog. Hope this helps someone in future.
SELECT [Latitude] AS [Latitude],
CAST([Latitude] AS INT) AS [Degrees],
REPLACE(CAST(([Latitude] - CAST([Latitude] AS INT)) * 60 AS INT), '-', '') AS [Minutes],
REPLACE(CAST((3600 * ([Latitude] - CAST([Latitude] AS INT))) - (CAST(([Latitude] - CAST([Latitude] AS INT)) * 60 AS INT) * 60) AS INT), '-', '') AS [Seconds]
FROM gis

Related

Hour:Minute format on an APEX chart is not possible

I use Oracle APEX (v22.1) and on a page I created a (line) chart, but I have the following problem for the visualization of the graphic:
On the y-axis it is not possible to show the values in the format 'hh:mi' and I need a help for this.
Details for the axis:
x-axis: A date column represented as a string: to_char(time2, 'YYYY-MM')
y-axis: Two date columns and the average of the difference will be calculated: AVG(time2 - time1); the date time2 is the same as the date in the x-axis.
So I have the following SQL query for the visualization of the series:
SELECT DISTINCT to_char(time2, 'YYYY-MM') AS YEAR_MONTH --x-axis,
AVG(time2 - time1) AS AVERAGE_VALUE --y-axis
FROM users
GROUP BY to_char(time2, 'YYYY-MM')
ORDER BY to_char(time2, 'YYYY-MM')
I have another problem to solve it in another way: I am not familiar with JavaScript, if the solution is only possible in this way. Because I started new with APEX, but I have seen in different tutorials that you can use JS. So, when JS is the only solution, I would be happy to get a short description what I must do on the page.
(I don't know if this point is important for this case: The values time1 and time2 are updated daily.)
On the attributes of the chart I enabled the 'Time Axis Type' under Settings
On the y-axis I change the format to "Time - Short" and I tried with different pattern like ##:## but in this case you see for every value and also on the y-axis the value '01:00' although the line chart was represented in the right way. But when I change the format to Decimal the values are shown correct as the line chart.
I also tried it with the EXTRACT function for the value like 'EXTRACT(HOUR FROM AVG(time2 - time1))|| ':' || EXTRACT(MINUTE FROM AVG(time2 - time1))' but in this case I get an error message
So where is my mistake or is it more difficult to solve this?
ROUND(TRUNC(avg(time2 - time1)/60) + mod(avg(time2 - time1),60)/100, 2) AS Y
will get close to what you want, you can set Y Axis minimum 0 maximum 24
then 12.23 means 12 hour and 23 minutes.

How to get latest result set based on the timestamp in amazon qldb?

I have many an IonStruct as follows.
{
revenueId: "0dcb7eb6-8cec-4af1-babe-7292618b9c69",
ownerId: "u102john2021",
revenueAddedTime: 2020-06-20T19:31:31.000Z,
}
I want to write a query to select the latest records set within a given year.
for example, suppose I have a set of timestamps like this -
A - 2019-06-20T19:31:31.000Z
B - 2020-06-20T19:31:31.000Z
C - 2020-06-20T19:31:31.000Z
D - 2021-07-20T19:31:31.000Z
E - 2020-09-20T19:31:31.000Z
F - 2020-09-20T19:31:31.000Z
If the selected year is between 2020 and 2021, I want to return records which having the latest timestamp.
in this case. E and F,
I tried many ways like
"SELECT * FROM REVENUES AS r WHERE r.ownerId = ? AND r.revenueAddedTime >= ? AND r.revenueAddedTime < ?"
Can anyone help me here?
Although I have no experience in qldb syntax, it seems to have similar properties to other db syntax in the sense that you can format your timestamps using these doc:
https://docs.aws.amazon.com/qldb/latest/developerguide/ql-functions.timestamp-format.html
https://docs.aws.amazon.com/qldb/latest/developerguide/ql-functions.to_timestamp.html
Once you format the timestamp, you may be able to do the > and < query syntax.

juliandate to normaldate in redshift

I have date like 117106, 117107 in an column which is of numeric type in redshift data base. Understood that the format is in Julian format. I wanted to change it to normal date format like yyyymmdd.
I tried applying the function to the column and it returns the value as below
select to_date(117106) - result 4393-07-10
Please help.
Thanks in advance
Here is how it is done.
The way it works is the first 3 digits is the century julian offset, and the last 3 are the day offset:
select dateadd(day,117106 % 1000,dateadd(year,(117106 /1000),convert(datetime,'01/01/1900')))-1
If I’ve made a bad assumption please comment and I’ll refocus my answer.
Thank you Rahul for the help.
I haven't tried the solution provided.However i have implemented the below solution as below to convert it into date format
trim(cast(to_char(dateadd(days,cast(right(x)as bigint)
+ datediff(days,'1900-01-02',to_date(cast(left((1900+(x/1000)),4) as char(4)) || '-01' || '-01','yyyy-mm-dd')),'1900-01-01'),
'YYYYMMDD')as decimal),0) as x
Can generate_series() to cover the julian day range you need and then use standard date functions
with julian_day as (
select generate_series as julian_day,
to_date(generate_series, 'J') as gregorian_date
from generate_series((2459865 - ( 10 * 365)), (2459865 + (10 * 365)), 1)
)
select
julian_day,
gregorian_date,
to_char(gregorian_date, 'IYYY') as iso_year,
date_part(year, gregorian_date) as year,
...
from julian_day

Calculating julian date in python

I'm trying to create a julian date in python and having major struggles. Is there nothing out there as simple as:
jul = juliandate(year,month,day,hour,minute,second)
where jul would be something like 2457152.0 (the decimal changing with the time)?
I've tried jdcal, but can't figure out how to add the time component (jdcal.gcal2jd() only accepts year, month and day).
Not a pure Python solution but you can use the SQLite in memory db which has a julianday() function:
import sqlite3
con = sqlite3.connect(":memory:")
list(con.execute("select julianday('2017-01-01')"))[0][0]
which returns: 2457754.5
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)
Answer one from Extract day of year and Julian day from a string date in python. No libraries required.
Answer two is a library from https://pypi.python.org/pypi/jdcal
The easiest: df['Julian_Dates']= df.index.to_julian_date(). you need to set your date time column to index (Use Pandas).
There is a way with using Astropy. First, change your time to a list (t). Second, change that list to astropy time (Time). Finally, compute your JD or MJD (t.jd t.mjd).
https://docs.astropy.org/en/stable/time/
For df:
t = Time(DF.JulianDates,format='jd',scale='utc')
A simple fudge the numbers script via wiki don't know either. Please note that this was written using Python 3.6 so I'm not sure it would work on Python 2.7 but this is also an old question.
def julian_day(now):
"""
1. Get current values for year, month, and day
2. Same for time and make it a day fraction
3. Calculate the julian day number via https://en.wikipedia.org/wiki/Julian_day
4. Add the day fraction to the julian day number
"""
year = now.year
month = now.month
day = now.day
day_fraction = now.hour + now.minute / 60.0 + now.second / 3600.0 / 24.0
# The value 'march_on' will be 1 for January and February, and 0 for other months.
march_on = math.floor((14 - month) / 12)
year = year + 4800 - march_on
# And 'month' will be 0 for March and 11 for February. 0 - 11 months
month = month + 12 * march_on - 3
y_quarter = math.floor(year / 4)
jdn = day + math.floor((month * 153 + 2) / 5) + 365 * year + y_quarter
julian = year < 1582 or year == (1582 and month < 10) or (month == 10 and day < 15)
if julian:
reform = 32083 # might need adjusting so needs a test
else:
reform = math.floor(year / 100) + math.floor(year / 400) + 32030.1875 # fudged this
return jdn - reform + day_fraction
Generally this was just to try for myself as the most common algorithm was giving me trouble. That works and if you search around for it and write your script using it as it comes in many languages. But this one has steps in the docs to try to keep it simple. The biggest decision is how often are you going to look for dates that are before Gregorian reform. That is why I never tested that yet but go ahead and play with it as it needs a lot of massaging. :-D At least I think is conforms to PEP8 even if it isn't up to best practices. Go ahead and pylint it.
You could just use source packages like PyEphem or whatever but you still would like to know what's going on with it so you could write your own tests. I'll link that PyEphem for you but there are lots of ready made packages that have Julian Day calculations.
Your best bet if you are doing lots of work with these types of numbers is to get a list of the constant ones such as J2000.
datetime.datetime(2000, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
datetime.datetime.toordinal() + 1721425 - 0.5 # not tested
# or even
datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
It's not so hard to figure these out if you get familiar with what datetime library does. Just for fun did you notice the PyEphem logo? I suspect it comes from something like this
One post that I saw seems to work but has no tests is jiffyclub
Now here is the more common way to calculate two values using a datetime object.
def jdn(dto):
"""
Given datetime object returns Julian Day Number
"""
year = dto.year
month = dto.month
day = dto.day
not_march = month < 3
if not_march:
year -= 1
month += 12
fr_y = math.floor(year / 100)
reform = 2 - fr_y + math.floor(fr_y / 4)
jjs = day + (
math.floor(365.25 * (year + 4716)) + math.floor(30.6001 * (month + 1)) + reform - 1524)
if jjs < ITALY:
jjs -= reform
return jjs
# end jdn
def ajd(dto):
"""
Given datetime object returns Astronomical Julian Day.
Day is from midnight 00:00:00+00:00 with day fractional
value added.
"""
jdd = jdn(dto)
day_fraction = dto.hour / 24.0 + dto.minute / 1440.0 + dto.second / 86400.0
return jdd + day_fraction - 0.5
# end ajd
It may not be the best practice in Python but you did ask how to calculate it not just get it or extract it although if that is what you want those questions have been answered as of late.
Try https://www.egenix.com/products/python/mxBase/mxDateTime/
First construct a DateTime object via the syntax
DateTime(year,month=1,day=1,hour=0,minute=0,second=0.0)
Then you can use '.jdn' object method to get the value you are looking for.

Format or Pattern for Decimal Numbers to display on axis on google charts

Good Morning,
When ever we create data table with certain data for Column Chart i.e.
**['Year', '% of ToTal Revenues ', '% of Total orders'],
['Feb12-July12', 0.25, 0.36],
['Aug12-Jan12', 0.58, 0.69],
['Feb13-July14', 0.47, 0.14],
['Aug13-Jan14', 0.62, 0.84]**
in the out put especially on VAxis the graph was displaying 0.1 to 0.98..
but when i a want to append % symbol to the given input values like 0.01%,0.02%,to 0.98% it was converting decimal into natural numbers that for ex 0.65 into 65 so what type of pattern i have to pass forex VAxis:{format:'#.##%'}};
Please Help Me
Thanks in advance
If I undestood right, you want to keep it as decimals instead of 0.5 = 50%. This should do the trick:
vAxis:{format: '#.#\'%\'' }