How to change Time Zone in Alpha Vantage API - timezone

Can I change the time zone in the result from Alpha Vantage API? Here is an example of the output. It's currently in EST. I'd like to get it in IST.
'Meta Data': {
'1. Information': 'Intraday (1min) open, high, low, close prices and volume',
'2. Symbol': 'BSE:------',
'3. Last Refreshed': '2019-11-01',
'4. Output Size': 'Compact',
'5. Time Zone': 'US/Eastern
}
'Time Series (1min)': {
'2019-11-01 00:08:59': {
'1. open': '70.7500',
'2. high': '70.7500',
'3. low': '70.7500',
'4. close': '70.7500',
'5. volume': '0'
},

Welcome to StackOverflow!
Right now the time zone that is returned is the only time zone you will receive from the API. However, if you're pulling the data in with a python script. You can always convert it to your time zone of choice.
from alpha_vantage.timeseries import TimeSeries
from datetime import datetime
import pytz
ts = TimeSeries()
data, meta_data = ts.get_daily('TSLA')
format = '%Y-%m-%d %H:%M:%S'
datetime = datetime.strptime(meta_data['3. Last Refreshed'], format)
old_timezone = pytz.timezone(meta_data['5. Time Zone'])
new_timezone = pytz.timezone("Asia/Calcutta")
# returns datetime in the new timezone
my_timestamp_in_new_timezone = old_timezone.localize(datetime).astimezone(new_timezone)
print(my_timestamp_in_new_timezone.strftime(format))
You could run a method that just converts all the times to whatever timezone you want when you pull the data

ts.get_daily('TSLA') should be changed to ts.get_intraday('TSLA').

Related

Converting Date to "/Date(631148400000+0100)/" string in Swift

I need to convert Swift Date object to date ticks string like "/Date(631148400000+0100)/".
The following link tells me how to convert date ticks string to Date object but not the vice-versa:
How to convert date like \/Date(1440156888750-0700)\/ to something that Swift can handle?
How can I do that?
Thanks in advance.
From Stand-Alone JSON Serialization:
DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.
And from Use JSON.NET to parse json date of format Date(epochTime-offset)
... In this screwy format, the timestamp portion is still based solely on UTC. The offset is extra information. It doesn't change the timestamp. You can give a different offset, or omit it entirely and it's still the same moment in time.
So the number of ticks is the number of milliseconds since Januar 1, 1970 GMT. Adding a time zone specification would only change how the
date is presented locally in .NET, and one can simply omit that part
when generating a JSON date string:
extension Date {
var jsonDate: String {
let ticks = lround(timeIntervalSince1970 * 1000)
return "/Date(\(ticks))/"
}
}
Example:
print(Date().jsonDate) // /Date(1481446227993)/

How can I add timezone to Esper queries?

I am using Esper & I need to filter events by their timestamp. The events come from an external source.
The challenge is that the cutoff instant is at a different timezone than the events` timestamp, e.g. the cutoff instant is at 3:30 CET (e.g. Prague time) while the timestamp field of the event is at UTC.
This poses a problem when the timezone shifts to Daylight Savings Time, because the cutoff instant needs to be modified in the query. E.g. in this case, if the cutoff instant is 3:30 CET, during winter time it would be on 2:30 UTC and during DST it would be on 1:30 UTC. It means that I have to change the query when the time shifts into and out of DST.
This is the current query:
SELECT *
FROM my_table
WHERE timestamp_field.after( timestamp.withtime(2,30,0,0) )
I would like to have a robust solution that will save me the hassle of changing the cutoff timestamp queries every few months. Can I add the timezone to the query statement itself? Is there any other solution?
It may help to add an event property to the event that represents UTC time i.e. normalize the event timestamp to UTC and use the normalized property instead.
The query could also use a variable instead of the hardcoded numbers. Another option would perhaps be changing Esper source to take in a timezone for some func.s
After struggling unsuccessfully with trying ot do it in the WHERE caluse or using a Pattern, I managed to solve the issue using a [Single-Row Function plugin][1].
I pass the plugin function the cutoff hour, timezone & event timezone and compute the cutoff hour in the event's timezone.
My query changed to:
SELECT *
FROM my_table
WHERE timestamp_field.after( timestamp.withtime(
eventTZHour(2, 'UTC', 'Europe/Prague'), 30, 0, 0) )
I added the Java implementation in a class:
public class EsperPlugins {
public int eventTZHour(int hour, String eventTZ, String cutoffTZ) {
// return tz calculations
}
}
and finally registered the plugin in esper.cfg.xml:
<esper-configuration>
<plugin-singlerow-function name="eventTZHour"
function-class="EsperPlugins"
function-method="eventTZHour"/>
</esper-configuration>
[1]: http://www.espertech.com/esper/release-5.2.0/esper-reference/html/extension.html#custom-singlerow-function from esper's docs

Timezone Offset in Angular JS and Rails

Background: I'm building an app with Angular JS as web interface and Rails API. The problem I am having is passing a date from Angular to Rails.
Issue: I have a form with a Date of Birth date field, when a user inputs his DOB say March 1st, 1985, Angular interprets it as 1985-03-01 00:00 +0800 (if you're in Hong Kong or Singapore) and sends a request to Rails. The first thing Rails does with it is to convert it to UTC, which means the datetime is now 1985-02-28 16:00 UTC. Therefore, when the date is saved to the database date column, it becomes Feb 28, 1985.
Solution for now: What I'm doing now is on Angular side, I get the Timezone offset hours and add it to the date, so instead of 1985-03-01 00:00 +0800, it is now 1985-03-01 08:00 +0800. When Rails get it, it converts to 1985-03-01 00:00 UTC and so saves the correct date to db. However, I believe this is a better alternative to tackle this issue.
Thinking about parsing just the date in Rails, yet the params[:dob] I see is already UTC by the time I get it. Would love to know if there is a better practice than my current solution. Thank you for any comment and feedback.
This problem is actually quite common, and stems from two separate but related issues:
The JavaScript Date object is misnamed. It's really a date + time object.
The JavaScript Date object always takes on the characteristics of the time zone for the environment in which it is running in.
For a date-only value like date-of-birth, the best solution to this problem is to not send a full timestamp to your server. Send just the date portion instead.
First, add 12 hours to the time, to use noon instead of midnight. This is to avoid issues with daylight saving time in time zones like Brazil, where the transition occurs right at midnight. (Otherwise, you may run into edge cases where the DOB comes out a day early.)
Then output the date portion of the value, as a string in ISO format (YYYY-MM-DD).
Example:
var dt = // whatever Date object you get from the control
dt.setHours(dt.getHours() + 12); // adjust to noon
var pad = function(n) { return (n < 10 ? '0' : '') + n; }
var dob = dt.getFullYear() + '-' + pad(dt.getMonth()+1) + '-' + pad(dt.getDate());
Another common way to do this is:
var dt = // whatever Date object you get from the control
dt.setHours(dt.getHours() + 12); // adjust to noon
dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset()); // adjust for the time zone
var dob = dt.toISOString().substring(0,10); // just get the date portion
On the Rails side of things, use a Date object instead of a DateTime. Unlike JavaScript, the Rails Date object is a date-only object - which is perfect for a date-of-birth.

User friendly timezone names from tz database format

I have timezones in the following array format:
'America/New_York' => '(GMT-05:00) Eastern Time (US & Canada)',
'Europe/Lisbon' => '(GMT) Greenwich Mean Time : Lisbon',
etc.
How do I go about displaying a user-friendly summer/daylight savings time dependent timezone identifier to the user?
For example, displaying the time now in New York would append "(EDT)" to the time, which would make sense for local users. I want to avoid having to display ((GMT-05:00) Eastern Time (US & Canada)) or just (GMT-05:00), which isn't strictly accurate all year round.
Ideally then, is there a web service/database that can take a tz string in the format "America/New_York", and a timestamp as paramters and return the abbreviation in the formats here?
strftime's %Z format specifier gives you this abbreviation. You didn't say what programming language you are using, but most programming languages give you access to strftime in one way or another.
Python:
import pytz
from datetime import datetime
here = pytz.timezone('Asia/Tokyo')
print here.localize(datetime.utcnow()).strftime("%Z")
there = pytz.timezone('America/Montreal')
print there.localize(datetime.utcnow()).strftime("%Z")
PHP:
date_default_timezone_set("Asia/Tokyo");
echo strftime("%Z");
date_default_timezone_set("America/Montreal");
echo strftime("%Z");

Problem in getting DST time?

I am trying to get the time of other GMT value by using
Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone(gmt));
but how can i get the DST time at that time zone.
The TimeZone class provides a getDSTSavings() method for a specific TimeZone Object. (JavaDoc: "Returns the amount of time to be added to local standard time to get local wall clock time.")
The Calendar interface provides two getOffset() methods, which let you find out the offset from UTC. (JavaDoc: "Returns the offset of this time zone from UTC at the specified date. If Daylight Saving Time is in effect at the specified date, the offset value is adjusted with the amount of daylight saving. ")
please see this piece of code to grok the complicated ways of java time:
#Test
public void testDST() {
final TimeZone met = TimeZone.getTimeZone("MET");
Calendar gc = new GregorianCalendar(met);
final long timeInMillis = gc.getTimeInMillis();
final long gmtTime= timeInMillis-(gc.getTimeZone().getOffset(timeInMillis));
final Date gmtDate = new Date(gmtTime);
System.out.printf("%-40s: %tc\n%-40s: %tc\n%-40s: %tc\n%-40s: %d\n%-40s: %d",
"new Date() (local timezone)",new Date(),
"UTC", gmtDate ,
"now from Calendar with TC GMT+02:00",gc,
"zoneoffset",gc.get(Calendar.ZONE_OFFSET),
"dst savings",met.getDSTSavings());
}
You can also define your own SimpleTimeZone and provide custom DST rules, however, i have not found out how to get this information from the predefined TimeZones.
You should also be aware, that if TimeZone.getTimeZone(TZName) does not find the specified timezone, it does not throw an exception, but it just uses GMT, which can cause major misunderstandings.
You can find all this information (and a lot more) in javadoc for Calendar, TimeZone, Date, etc.
There are few methods available in java.util.TimeZone to get Daylight Saving Time. Please check out the BlackBerry Java Docs page.

Resources