daylight saving time influences the result of mktime - awk

I have an issue trying to get the exact GPS time. Looks like the issue is related to command mktime used in the code.
To get the correct GPS time I have added -2 hrs in UTC.
But the purpose is to have a code to calculate the GPS time automatically and don't use manually changes at UTC-2 as an example
Input file GMT time ( > 3 hrs in local time )
18/05/21 08:18:29
18/05/21 08:20:25
18/05/21 08:21:02
When I run the code below, got 1 hour less :
gawk -F'[/: ]' -v ts=$(date -d'01/06/1980' +%s) \
-v lap=18 '{$1="" d=sprintf(20$0);
print mktime(d)+lap-ts }' file
result output GPS TIME ( < 1 hr )
1210922327
1210922443
1210922480
When I run the code below, got exactly the correct GPS time.
gawk -F'[/: ]' -v ts=$(TZ=UTC-2 date -d'1/6/1980 0:00' +%s) \
-v lap=18 '{$1="" d=sprintf(20$0);
print mktime(d)+lap-ts }' file
Result output GPS TIME ( exactly time: OUTPUT DESIRED)
1210925927
1210926043
1210926080
Thanks in advance

What you are encountering is mostly related to the time-zone settings of your system. Due to Daylight Saving Time, your time-zone shifted one hour which causes the discrepancy. A very nice post of detecting DST, can be found here. Copying its examples, we can show that for the time-zone TZ=Europe/Stockholm, the time-zone changes to summer time depending on the date :
$ TZ=Europe/Stockholm date +%Z # CET or CEST depending of when its run
$ TZ=Europe/Stockholm date --date=20170101 +%Z # CET
$ TZ=Europe/Stockholm date --date=20170601 +%Z # CEST
$ TZ=CET date --date=20170101 +%Z # CET
$ TZ=CET date --date=20170601 +%Z # CEST, note that its auto adjusted to CEST
and therefore it will for sure have an effect on the epoch time which is given from 1970-01-01T00:00:00 UTC. With zdump we see when DST comes into affect :
$ zdump -v /usr/share/zoneinfo/Europe/Stockholm | grep 2018
/usr/share/zoneinfo/Europe/Stockholm Sun Mar 25 00:59:59 2018 UTC = Sun Mar 25 01:59:59 2018 CET isdst=0 gmtoff=3600
/usr/share/zoneinfo/Europe/Stockholm Sun Mar 25 01:00:00 2018 UTC = Sun Mar 25 03:00:00 2018 CEST isdst=1 gmtoff=7200
/usr/share/zoneinfo/Europe/Stockholm Sun Oct 28 00:59:59 2018 UTC = Sun Oct 28 02:59:59 2018 CEST isdst=1 gmtoff=7200
/usr/share/zoneinfo/Europe/Stockholm Sun Oct 28 01:00:00 2018 UTC = Sun Oct 28 02:00:00 2018 CET isdst=0 gmtoff=3600
and this is seen in the epoch time as :
$ TZ=Europe/Stockholm date -d "2018-03-25 01:59:59" +%s
1521939599
$ TZ=Europe/Stockholm date -d "2018-03-25 03:00:00" +%s
1521939600
$ TZ=Europe/Stockholm date -d "2018-03-25 02:00:00" +%s
date: invalid date ‘2018-03-25 02:00:00’
As you see, for TZ=Europe/Stockholm, the time 2018-03-25T02:00:00 does not exist and the other two are only 1 sec apart.
Summary, what does this all mean: it essentially means that your system automatically compensates for DST, unless your TZ is UTC. And this play a role on all date related command such as systime(), date or even Awk's mktime().
Can we avoid DST compensation with awk:
Since the OP wants the GPS-time, i.e. the total seconds since 1980-01-06T00:00:00, you essentially subtract two times. So if both are computed in the same TZ without DST correction, you always get the correct result. There are 2 ways to do this :
execute your command in a specific timezone:
By forcing the system to work in a single TZ (such as UTC, UTC+2, ...), there will be no DST correction. For the OP's question, the TZ of interest is UTC.
$ TZ="UTC" awk 'BEGIN { ts = mktime("1980 01 06 00 00 00") }
{ datespec="20"$0; gsub(/[/:]/," ",datespec);
print mktime(datespec) + lap - ts
}' lap=18 file
or from awk 4.20 onwards you can tell mktime() to assume that the date is in UTC by using the UTC flag. (mktime(datespec [, utc-flag ]))
$ awk 'BEGIN { ts = mktime("1980 01 06 00 00 00",1) }
{ datespec="20"$0; gsub(/[/:]/," ",datespec);
print mktime(datespec,1) + lap - ts
}' lap=18 file
both result in the following output.
1210925927
1210926043
1210926080
In both cases, you don't need to worry about your system-timezone and all the mumbo-jumbo related to daylight savings time.
disable DST correction with mktime: When adding a DST entry to the datespec part of mktime, you can tell the system to alwyas work in DST or not or let the system figure it out by himself. The latter is what you do not want. datespec is a string of the form YYYY MM DD HH MM SS [DST]. And this brings it down too:
$ awk 'BEGIN { ts = mktime("1980 01 06 00 00 00 0") }
{ datespec="20"$0; gsub(/[/:]/," ",datespec);
print mktime(datespec" 0") + lap - ts
}' lap=18 file
Documentation for mktime awk 4.2.0 onwards:
mktime(datespec [, utc-flag ])
Turn datespec into a timestamp in the same form as is returned by systime(). It is similar to the function of the same name in ISO C. The argument, datespec, is a string of the form "YYYY MM DD HH MM SS [DST]". The string consists of six or seven numbers representing, respectively, the full year including century, the month from 1 to 12, the day of the month from 1 to 31, the hour of the day from 0 to 23, the minute from 0 to 59, the second from 0 to 60,55 and an optional daylight-savings flag.
The values of these numbers need not be within the ranges specified; for example, an hour of -1 means 1 hour before midnight. The origin-zero Gregorian calendar is assumed, with year 0 preceding year 1 and year -1 preceding year 0. If utc-flag is present and is either non-zero or non-null, the time is assumed to be in the UTC time zone; otherwise, the time is assumed to be in the local time zone. If the DST daylight-savings flag is positive, the time is assumed to be daylight savings time; if zero, the time is assumed to be standard time; and if negative (the default), mktime() attempts to determine whether daylight savings time is in effect for the specified time.
If datespec does not contain enough elements or if the resulting time is out of range, mktime() returns -1.

Related

Convert Time and Date in string to date VB.net

I'm using RSS feeds from multiple sources and I'm sorting the feeds by date. However, the dates I receive are in different time zones.
This is the format of some of the date strings that I get:
Wed 08 Dec 2021 01:40:31 -0500
Wed 08 Dec 2021 11:11:19 -0600
The "-500' indicates the time zone which is UTC-5. I need to use that "-0500" to convert this string into a date and the date needs to be only in UTC.
Basically from "Wed 08 Dec 2021 01:40:31 -0500" to "12/08/2021 06:40:31"
I've managed to split the string up to sort by date but because of the time difference, it doesn't really help.
Is there coding which I can use to convert the string as-is into date and only UTC time? Or is there just a place where I can start?
Thank you in advance.
Using DateTime.ParseExact, you specify a format to convert from, and that can include "zzz" for the timezone offset. You can also specify that you want the result in UTC:
Dim s = "Wed 08 Dec 2021 01:40:31 -0500"
Dim d = DateTime.ParseExact(s, "ddd dd MMM yyyy HH:mm:ss zzz", Nothing, Globalization.DateTimeStyles.AdjustToUniversal)
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"))
Console.WriteLine(d.Kind.ToString())
Outputs:
2021-12-08 06:40:31
Utc
Of course, format the result as you desire.
Alternatively, if you need to, you can keep the offset by using a DateTimeOffset structure and adjust it to UTC for representation as a string:
Dim s = "Wed 08 Dec 2021 01:40:31 -0500"
Dim d = DateTimeOffset.ParseExact(s, "ddd dd MMM yyyy HH:mm:ss zzz", Nothing)
Console.WriteLine(d.ToUniversalTime.ToString("yyyy-MM-dd HH:mm:ss"))
Outputs:
2021-12-08 06:40:31

How do you convert timestamp with GMT timezone in Redshift?

How do you convert a string with DOW and GMT information to timestamptz in Redshift?
Example: Mon Apr 01 2019 14:08:20 GMT-0400 (EDT)
Amazon Redshift is based on PostgreSQL. Therefore, with the use of TO_DATE function, along with timezone related clauses, we could try the following.
SELECT
TO_TIMESTAMP('Mon Apr 01 2019 14:08:20 GMT-0400 (EDT)', 'XXX Mon DD YYYY HH:MI:SS')
AT TIME ZONE REGEXP_REPLACE('Mon Apr 01 2019 14:08:20 GMT-0400 (EDT)', '^.*(...).$', '\\1');
This results in the following.
Unfortunately, it doesn't seem like we can do this conversion in one go because time zone related format flags are valid for TIMESTAMPTZ only.

convert a string to oracle sql timestamp Mon Aug 19 2019 08:21:48 GMT-0700 (PDT)

Greeting Community.
I saw similar examples in Java but how do we do it it SQL in particular Oracle.
For now I just do this which it works because we are in PDT timezone.
-Thx for the help!
with xx as (
select replace('Mon Aug 19 2019 08:21:48 GMT-0700 (PDT)',' GMT-0700 (PDT)','') as dt from dual
)
select to_date(dt,'DY MON DD YYYY HH24:MI:SS') from xx
The input is a timestamp with time zone. It has redundant information about the time zone; some of that must be stripped away. For example, if you choose to trust PDT and ignore the GMT offset, you could do something like this:
with xx as (
select regexp_replace('Mon Aug 19 2019 08:21:48 GMT-0700 (PDT)','GMT-\d{4} \(|\)')
as str_ts_with_tz
from dual
)
select to_timestamp_tz(str_ts_with_tz,'Dy Mon DD YYYY HH24:MI:SS TZD')
as oracle_ts_with_tz
from xx
;
ORACLE_TS_WITH_TZ
---------------------------------------
2019-08-19 08:21:48 America/Los_Angeles
Note that the resulting data type is timestamp with time zone. You can further cast this as timestamp or as date (simply discarding the time zone information) if needed; this is a simple operation, internal to Oracle. But that will lose information; think twice before you do that.
Note also that the timestamp is presented in a different format in my output, compared to your input. This is because my NLS_TIMESTAMP_TZ_FORMAT is 'yyyy-mm-dd hh24:mi:ss tzr'.
If you are wondering why you must make a choice (which, then, means "why you need to delete part of the input string first") regarding the time zone information: PDT is simply not the same as GMT-0700. It may be that in summer, but not in winter. Oracle won't accept such self-contradicting nonsense as input to its functions. Either it's GMT-0700 or it's PDT, it can't be both. And, you can't just use REPLACE (not easily, anyway), because what must be replaced may have variable characters in it.

Converting a timestamp in milliseconds in Postgres

I have a timestamp in milliseconds:
1420066991000
That translates into UTC:
Wed Dec 31 2014 23:03:11
and local time:
Thu Jan 01 2015 00:03:11
However if I try to convert it into a timestamp in Postgres, using to_timestamp, it gives me a wrong datetime:
select to_timestamp(1420066991000);
46970-02-17 13:03:20+00
Since to_timestamp, expects a double precision input, I also did this:
select to_timestamp(1420066991000.0);
46970-02-17 13:03:20+00
but the results are the same.
Am I missing something in my Postgres configuration, like some timezone setting? or is it a bug?
to_timestamp() converts unix time, that is time in seconds. Since you have data in miliseconds you should divide it by 1000.
select to_timestamp(1420066991000/1000);

Rails daylight savings time not accounted for when using DateTime.strptime

I've been working on parsing strings and I have a test case that has been causing problems for me. When parsing a date/time string with strptime, Daylight Savings Time is NOT accounted for. This is a bug as far as I can tell. I can't find any docs on this bug. Here is a test case in the Rails console. This is ruby 1.9.3-p215 and Rails 3.2.2.
1.9.3-p125 :049 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z")
=> Sun, 15 Apr 2012 10:00:00 -0600
1.9.3-p125 :050 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z").utc
=> Sun, 15 Apr 2012 16:00:00 +0000
1.9.3-p125 :051 > dt = DateTime.strptime("2012-04-15 10:00 Central Time (US & Canada)", "%Y-%m-%d %H:%M %Z").utc.in_time_zone("Central Time (US & Canada)")
=> Sun, 15 Apr 2012 11:00:00 CDT -05:00
As you can see, I have to convert to utc and then back to the timezone to get DST to be properly interpreted, but then the time is shifted one hour as well, so it's not what I parsed out of the string. Does someone have a workaround to this bug or a more robust way of parsing a date + time + timezone reliably into a DateTime object where daylight savings time is properly represented? Thank you.
Edit:
Ok, I found a workaround, although I'm not sure how robust it is.
Here is an example:
ActiveSupport::TimeZone["Central Time (US & Canada)"].parse "2012-04-15 10:00"
This parses the date/time string into the correct timezone. I'm not sure how robust the parse method is for handling this so I'd like to see if there is a better workaround, but this is my method so far.
This is a frustrating problem. The Rails method you're looking for is Time.zone.parse. First use DateTime.strptime to parse the string, then run it through Time.zone.parse to set the zone. Check out the following console output:
> Time.zone
=> (GMT-06:00) Central Time (US & Canada)
> input_string = "10/12/12 00:00"
> input_format = "%m/%d/%y %H:%M"
> date_with_wrong_zone = DateTime.strptime(input_string, input_format)
=> Fri, 12 Oct 2012 00:00:00 +0000
> correct_date = Time.zone.parse(date_with_wrong_zone.strftime('%Y-%m-%d %H:%M:%S'))
=> Fri, 12 Oct 2012 00:00:00 CDT -05:00
Notice that even though Time.zone's offset is -6 (CST), the end result's offset is -5 (CDT).
Ok, here is the best way I've found to handle this so far. I created a utility method in a lib file.
# Returns a DateTime object in the specified timezone
def self.parse_to_date(date_string, num_hours, timezone)
if timezone.is_a? String
timezone = ActiveSupport::TimeZone[timezone]
end
result = nil
#Chronic.time_class = timezone # Trying out chronic time zone support - so far it doesn't work
the_date = Chronic.parse date_string
if the_date
# Format the date into something that TimeZone can definitely parse
date_string = the_date.strftime("%Y-%m-%d")
result = timezone.parse(date_string) + num_hours.to_f.hours
end
result
end
Note that I add hours onto the time manually because Chronic.parse wasn't as robust as I liked in parsing times - it failed when no trailing zeros were added to a time, for example, as in 8:0 instead of 8:00.
I hope this is useful to someone. Parsing date/time/timzone strings into a valid date seems to be a very common thing, but I was unable to find any parsing code that incorporated all three together.