Poco::LocalDateTime::timestamp() not converting timestamps to UTC - poco-libraries

According to the header file of Poco::Timestamp, timestamps are in UTC, see Timestamp documentation. If timestamps are in UTC, shouldn't a method converting a Poco::LocalDateTime to Poco::Timestamp make sure that the returned timestamp is in UTC? Currently, Poco::LocalDateTime::timestamp() does not do this, and the returned timestamp is in local time.
It's especially strange since the assignment operator Poco::LocalDateTime::operator = (const Timestamp& timestamp) does a UTC to local time conversion. The following code asserts because of this:
Poco::LocalDateTime local1 = Poco::LocalDateTime( 2020, 1, 30 );
Poco::Timestamp timestamp = local1.timestamp();
Poco::LocalDateTime local2 = timestamp;
assert( local1 == local2 );
local1 will not have the same value as local2 in this example. Am I the only one who think this is strange behavior?

If you look at LocalDateTime::timestamp() you will see that it converts the timestamp before returning via Timestamp::fromUtcTime so that function returns a Timestamp in Local time, not UTC time.
You can use the Timestamp::utcTime() function or the Timestamp::raw() function but those return different types to prevent you from accidentally doing the wrong thing.
What are you actually trying to achieve here?

Related

Parsing a datetime string to local time in rust chrono

Having trouble with a simple problem. I have a string that does not include timezone information that I need to parse into a DateTime struct. I can get it as UTC, but not local:
let from = NaiveDateTime::parse_from_str(&start_date, "%Y-%m-%dT%H:%M:%S")?;
let from_utc = DateTime::<Utc>::from_utc(from, Utc);
You need Local.from_local_datetime() to convert a NaiveDateTime into a DateTime<Local>:
let from: NaiveDateTime = start_date.parse().unwrap();
let date_time = Local.from_local_datetime(&from).unwrap();
Admittedly, this isn't really easy to find in the documentation.
The first line you have works fine as well. For this particular format (RFC3339), it's easier to use str::parse(), though.

Issue in converting Unix timestamp get from moment to normal date

I am using moment().valueOf() to get unix timestamp and to get the normal time from unix time i'm using moment.unix(unix_time).format('LLL') when the unix value is 1606985226404 getting the anser as May 2, 52893 6:36 AM which is incorrect. What is the issue with this?
According to the documentation of Moment.JS, moment() works with milliseconds.
So:
const unix_time = moment().valueOf(); // return epoc in milliseconds
const now = moment.unix(unix_time / 1000).format('LLL').
That's the trick.

splunk mysearchbar.timerange.val() datetime to UTC

I am using Splunk 6.2.X along with Django bindings to create a Splunk app.
To get access to the earliest/latest dates from the timerange picker, am using the following in my JS.
mysearchbar.timerange.val()
Am getting back a map where the values are in epoch format:
Object {earliest_time: 1440122400, latest_time: 1440124200}
When I convert them using moment using the following, I get different datetime than expected:
> moment.unix('1440122400').utc().toString()
"Fri Aug 21 2015 02:00:00 GMT+0000"
However, the time does not correspond to the values that have been selected on the time range picker i.e. 08/20/2015 22:00:00.000
Am not sure what the difference is getting caused by? Am sure tht the timezone is not the factor as the time difference is erratically not equivalent to derive using simple timezone add/subtract.
I was wondering if this behaviour can be explained as to how to get the Splunk epoch datetime to UTC would be helpful.
I was able to get rid of the timezone issue by performing the following:
Setting the timezone of the Splunk engine to UTC in props.conf as follows:
TZ = GMT
Setting up the CentOS (the server hosting Splunk) to UTC
Hope this helps anyone else who stumbles upon similar issues.
Thanks.

Getting local time for future events based off UTC

I'm working on a script that will look up an event on a community Google Calendar (using Eastern Time Zone) and successfully convert it to the local user's timezone. Because it is a community Google Calendar, I cannot set the time to display as UTC, which would theoretically make this that much easier. Here is a step-by-step process that I am attempting to create:
Get the event time as it stands (Eastern time) from Google Calendar. This is done quite easily using the API and json format.
Get the Eastern timezone offset based on the event time using Google Maps API. Again, this is easily done.
Convert the Event time from Eastern to UTC, which I believe is done by adding the offset to the Event time.
Calculate the local timezone/UTC timezone difference based on the future date.
Return the local time for the event by adding step 4's result to the UTC event's time.
However, no matter what I do, it seems to not work the way I want it. Here is the code as it stands:
local function get_local_time(dateTime)
local xyear, xmonth, xday = string.match(dateTime, "(%d+)%-(%d+)%-(%d+)") -- Date format is displayed as yyyy-mm-dd
local xhour, xmin = string.match(dateTime, "%a(%d+):(%d+)") -- Time format is displayed as Thh:mm
local event_time = os.time({year = xyear, month = xmonth, day = xday, hour = xhour or 23, min = xmin or 59, sec = 0}) -- Gets epoch time for event time
async_ok, async = pcall (require, "async") -- Asynchronous lookup functions
if not json then json = require 'json' end
tzpage = "https://maps.googleapis.com/maps/api/timezone/json?location=28.4158,-81.2989&timestamp=" .. event_time .. "&key=" .. key -- Gets offset data for Eastern Time Zone
if async_ok then
tzrpage = async.request(tzpage, "HTTPS")
end
retval, page, status, headers, full_status = tzrpage:join()
tzrpage = nil
if status == 200 then
tzopage = json.decode(page)
end
local eastern_offset = tzopage.rawOffset+tzopage.dstOffset -- Adds the offset information together (includes Daylight Savings)
local utc_event_time = event_time+eastern_offset -- Sets UTC's time for the event
local utctime, localtime = os.date("!*t", utc_event_time), os.date("*t", utc_event_time) -- Sets table data for events based on UTC's time of the event
localtime.isdst = false
local localoffset = os.difftime(os.time(utctime), os.time(localtime)) -- Sets the time difference between UTC and local time at the time of the event UTC
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset)) -- Should return local time of the event
end
But when I do something like the following:
print(get_local_time("2015-10-31T01:15:00"))
it returns
Friday, October 30 2015 at 02:15PM
when it should be returning
Friday, October 30 2015 at 10:15PM
as I'm Pacific time.
If I change
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset))
to
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time+localoffset))
I get
Saturday, October 31 2015 at 04:15AM
Which again, is incorrect.
Where am I going wrong with this script? As a side note, the async is a client dependency, but it's essentially http.request.
Convert the Event time from Eastern to UTC, which I believe is done by adding the offset to the Event time.
Subtracting.
The offset shown in a timestamp is a signed number. It's already been "added" to UTC to generate the local time, so the inverse operation would be to subtract it. With -0400 being negative, you'd need to subtract negative 4 hours to convert back to UTC.

Python 3: timestamp to datetime: where does this additional hour come from?

I'm using the following functions:
# The epoch used in the datetime API.
EPOCH = datetime.datetime.fromtimestamp(0)
def timedelta_to_seconds(delta):
seconds = (delta.microseconds * 1e6) + delta.seconds + (delta.days * 86400)
seconds = abs(seconds)
return seconds
def datetime_to_timestamp(date, epoch=EPOCH):
# Ensure we deal with `datetime`s.
date = datetime.datetime.fromordinal(date.toordinal())
epoch = datetime.datetime.fromordinal(epoch.toordinal())
timedelta = date - epoch
timestamp = timedelta_to_seconds(timedelta)
return timestamp
def timestamp_to_datetime(timestamp, epoch=EPOCH):
# Ensure we deal with a `datetime`.
epoch = datetime.datetime.fromordinal(epoch.toordinal())
epoch_difference = timedelta_to_seconds(epoch - EPOCH)
adjusted_timestamp = timestamp - epoch_difference
date = datetime.datetime.fromtimestamp(adjusted_timestamp)
return date
And using them with the passed code:
twenty = datetime.datetime(2010, 4, 4)
print(twenty)
print(datetime_to_timestamp(twenty))
print(timestamp_to_datetime(datetime_to_timestamp(twenty)))
And getting the following results:
2010-04-04 00:00:00
1270339200.0
2010-04-04 01:00:00
For some reason, I'm getting an additional hour added in the last call, despite my code having, as far as I can see, no flaws.
Where is this additional hour coming from?
# Ensure we deal with `datetime`s.
date = datetime.datetime.fromordinal(date.toordinal())
(That's chopping off the time-of-day completely, as ‘ordinal’ is only a day number. Is that what you meant to do? I suspect not.)
Anyway, as Michael said, datetime.fromtimestamp gives you a naïve datetime corresponding to what local time for that POSIX (UTC) timestamp would be for you. So when you call —
date = datetime.datetime.fromtimestamp(adjusted_timestamp)
you're getting the local time for the POSIX timestamp representing 2010-04-04T00:00:00, which of course in BST is an hour ahead. This doesn't happen in the return direction because your epoch is in January, when BST is not in force. (However your EPOCH would also be completely off if you weren't in the UK.)
You should replace both your uses of datetime.fromtimestamp with datetime.utcfromtimestamp.
It's sad that datetime continues the awful time tradition of keeping times in local time. Calling them ‘naïve’ and taking away the DST flag just makes them even worse. Personally I can't stand to use datetime, preferring integer UTC timestamps for everything (converting to local timezones for formatting only).
Judging by your profile, you're in the UK. That means you're currently running on UTC+1 due to DST.
If I take your timestamp and run it through datetime.fromtimestamp on Python 2.6 (I know you use Python 3, but this is what I have), that shows me that it believes it refers to 2010-04-04 02:00:00 - and I'm in CEST, so that's UTC+2.
Running datetime.fromtimestamp(0), I get that the epoch is 1970-01-01 01:00:00. This then shows me that it is correctly adding only a single hour (since January 1st is outside of DST, and the epoch is midnight UTC on that date, it would be 01:00 here).
In other words, your problem is that you're sending in a time which has DST applied, but datetime_to_timestamp treats it as if DST didn't exist. timestamp_to_datetime, however, applies the DST.
Unfortunately, I don't know enough Python to know how you would solve this, but this should at least give you something to go on.

Resources