I am working on a chat app. I want to determine the time difference between UTC time zone and device current time zone. How to do that in swift3 ?
// Returns a Date initialized to the current date and time
let currentDate = Date()
// Returns the time zone currently used by the system
let timeZone = NSTimeZone.system
// Returns the difference in seconds between the receiver and Greenwich Mean Time at a given date.
let timeZoneOffset = timeZone.secondsFromGMT(for: currentDate) / 3600
print(timeZoneOffset, "hours offset for timezone", timeZone)
// example output for Denver (considers daylight saving time)
// -6 hours offset for timezone America/Denver (current)
Related
I am using multiple APIs and saving them to the database. I have one model called Station (it has a DateTime field and some other fields) and every API is for one station. These APIs come from devices that measure some variables and they get updated every 3 minutes.
I wrote a background task that calls a saveToDB function and stores them in the database. For example:
1. station A "some variables" 2022/10/1 13:10
2. station B "some variables" 2022/10/1 13:10
3. station A "some variables" 2022/10/1 13:13
4. station B "some variables" 2022/10/1 13:13
Now I need to take an average of every station every 10 minutes, 2 hours, week, month, and year.
There are 30 stations. How can I do this?
If your question is what the django code would look like to make these calculations, your should read up here on aggregation. Jump down to the "values()" section of the page. The code to group by station and calculate the average of all entries would be:
Station.objects.values('station_id').annotate(myAverage=Avg('some_variable'))
This will group all entries by station.
However, you can simplify by using a nested loop to isolate each station and run the average over each 10 minute interval. Not sure exactly what the conditions for which 10 minute intervals you need, but let's say you want each 10 minutes from yesterday. Something like:
from datetime import datetime, timedelta
from django.db.models import Avg
from .models import Station
def test():
# get yesterday's date at midnight
yesterday_at_midnight = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1)
# add 10 minutes to the yesterday_at_midnight variable
ten_minutes_after_midnight = yesterday_at_midnight + timedelta(minutes=10)
# set the start time to yesterday_at_midnight
start_time = yesterday_at_midnight
# set the end time to ten_minutes_after_midnight
end_time = ten_minutes_after_midnight
# loop over each station in the database
for s in Station.objects.all():
# loop over the next 143 10 minute intervals (24 hours - 1 interval)
for i in range(143):
# find all the Station objects that fall within the current 10 minute interval
stations = Station.objects.filter(station_id=s.station_id, created_at__gte=start_time, created_at__lt=end_time).aggregate(Avg('some_variable'))
# do something with this QuerySet
print(stations)
# increment the start and end times by 10 minutes
start_time += timedelta(minutes=10)
end_time += timedelta(minutes=10)
I have a dataset that uses Direct Query. I have a timestamp column and I am trying to add another column that will show the local time of that column for differnt users based on the selection from the slicer (which contains the list of countries). The new column should show the timezone based on the slicer list but I am not getting the right timezone.
I managed to connect to a timezonedb that will give me a list of offset for different timezones based on this article in this link: https://whitepages.tygraph.com/2020/10/dynamic-time-zone-conversion-using-power-bi/
This is what I have tried:
DAX measure: selected_offset = MAX(global_timezone[offset_days])
New column(local_time): date_column + [selected_offset]
**Start Timestamp: Timestamp column is saved using UTC+0
**selected_offset = SG timezone (UTC+8) = 0.3333
Error:
selected_offset = 0.583333 (instead of 0.3333)
Start Timestamp selected_offset local_time
04/13/2022 2:38 0.583333333 04/13/2022 16:38
04/13/2022 2:37 0.583333333 04/13/2022 16:37
04/13/2022 2:37 0.583333333 04/13/2022 16:37
Desired output: (see local_time column below)
Start Timestamp selected_offset local_time
04/13/2022 2:38 0.333333333 04/13/2022 10:38
04/13/2022 2:37 0.333333333 04/13/2022 10:37
04/13/2022 2:37 0.333333333 04/13/2022 10:37
Please let me know how to get the correct date time for local_time column based on slicer selection. Most solutions I found offer solution in Power Query which is something I cannot use at the moment due to DQ I am using for this dataset. Thanks!
I'm not sure if you are certain how this solution (from the article) is working.
First of all, we get the current UTC (UTC+0) from UTCNOW() function then we check the offset to other timezones. This means you should know what time zone your timestamp is from. You need to do two calculations, first subtract the offset from the "base column" and then add the offset to the desired time zone.
For example, if I want to show time for someone in America/Chicago and I have a column with the timestamp 2022-04-14 09:55 (UTC+2 Europe/Warsaw). Offset to this timezone is 0.08333. offset to America/Chicago -0.21
then full calculation is '2022-04-14 09:55' - (0.08333) + (-0.21) == 2022-04-14 02:55
As you all might already know, TODAY() function returns UTC time when published to Power BI Service.
Our requirement is to return the local (EST) date. As a solution, we created a custom measure that adds UTC offset hours for EST in NOW() and returns the resultant date.
However, this does not handle daylight saving changes as offset changes during these periods.
What are the possible ways to handle this?
You can try something like this:
ESTnow=
VAR currentTime = NOW()
VAR timeYear = YEAR(currentTime)
VAR dstStart = DATE(timeYear, 03, 14 - MOD((1+FLOOR(timeYear*5/4,1)),7)) + TIME(2,0,0)
VAR dstEnd = DATE(timeYear, 11, 7 - MOD((1+FLOOR(timeYear*5/4,1)),7)) + TIME(2,0,0)
RETURN IF(currentTime >= dstStart && currentTime <= dstEnd, currentTime - TIME(4,0,0), currentTime - Time(5,0,0))
Daylight savings start on the second Sunday of March and end on the first Sunday of November.
A more flexible way to convert UTC date/time for any location (time zone) in the world, and taking Daylight Saving into account, would be to use a Time API service like the one at https://www.timeanddate.com/services/api/time-api.html
I need a timestamp in a special format for an API call:
Dates are converted to UTC milliseconds elapsed since 12:00:00 midnight, January 1, 0001.
My first assumption was to use:
auto now = std::chrono::system_clock::now();
std::cout << "millisceconds since epoch: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()).count()
But of course the output is the time interval from the UNIX epoch
Thu Jan 1 00:00:00 1970
So for a now = "Wed Dec 12 13:30:00 2018" it returns 1544617800000ms.
How do I get the milliseconds elapsed since 12:00:00 midnight, January 1, 0001?
Context OSISoft API
The OSISoft API Documentation for specifying a date range is quite strange
Numeric Range Queries
The previous examples were Range Queries against string fields. Numeric values > can also be searched for with Range Queries.
The only fields that are indexed as numeric fields are the CreationDate and ChangeDate fields for the respective PI Point attributes. To index these fields > add them to the list of PI Point Attributes. This configuration may be viewed > or modified on the Settings page.
These date time values are indexed as numeric values via a conversion: Dates are converted to UTC milliseconds elapsed since 12:00:00 midnight, January 1, 0001.
In the following example query is a request for last changed date equal to or > greater than February 26th, 22:16:50.000 (This is Universal Time). This DateTime, following the aforementioned conversion, would be represented as numeric value: 63655280210000. Therefore the query submitted is:
https://MyServer/piwebapi/search/query?q=changedate:[63655280210000 TO *]
From this documention I have asked this question on how to get the milliseconds elapsed since 12:00:00 midnight, January 1, 0001.
I also linked the Question to PISquare
There is no defined way to calculate:
UTC milliseconds elapsed since 12:00:00 midnight, January 1, 0001.
Judging by the examples they are using the same algorithm as https://www.epochconverter.com/seconds-days-since-y0. To get the same result you can just add 719162 days to the unix epoch:
auto now = std::chrono::system_clock::now();
std::cout << "millisceconds since epoch: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch() + std::chrono::hours(24 * 719162)).count()
Note c++20 introduces std::chrono::days which you could use instead of 24 hours.
Depending on the resolution of your system clock you may need to cast to milliseconds before adding the offset to avoid overflows (719162 days is more than 2^64 nanoseconds).
This is easy using Howard Hinnant's date/time library:
#include "date/date.h"
#include <iostream>
std::chrono::milliseconds
convert(std::chrono::system_clock::time_point tp)
{
using namespace date;
using namespace std::chrono;
return (floor<milliseconds>(tp) +
(sys_days{1970_y/January/1} - sys_days{1_y/January/1})).time_since_epoch();
}
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << convert(system_clock::now()) << '\n';
}
convert simply adds the difference between the two epochs to the system_clock::time_point, truncated to milliseconds precision, and extracts the duration to return it as milliseconds.
This program for me just output:
63680221359193ms
The range on milliseconds is plenty big enough to handle this computation, but the range on your system_clock::time_point may not be. Thus it is important to truncate to milliseconds right away as done in the code above to avoid overflow.
I have to implement in my app where after a user had saved his recording, I will have to determine if 24 hours have passed from the creation date of that recording. So far what I have at the moment is just to determine if current date is not equal to the creation date. I really appreciate anybody's help, thanks in advance.
You can use UserDefault to save the date upon creation of the record. The syntax will be
UserDefaults.standard.set(Date(), forKey:"creationTime")
Whenever you want to check the saved date, retrieve it in this way
if let date = UserDefaults.standard.object(forKey: "creationTime") as? Date {
if let diff = Calendar.current.dateComponents([.hour], from: date, to: Date()).hour, diff > 24 {
//do something
}
}
You can easily check if the time interval since date is greater or equal to a TTL of 24 hours.
let start = Date()
let timeToLive: TimeInterval = 60 * 60 * 24 // 60 seconds * 60 minutes * 24 hours
let isExpired = Date().timeIntervalSince(start) >= timeToLive