Format UTC Time To Local Time - datetime

When you have a string that is formatted in UTC Time, how can I format it to a DateTime but local time?
For example, if I have the below code, it improperly formats my code (meaning incorrect time)
string dateformatted = "2017-01-10T11:13:00-07:00"
DateTime.Parse(Convert.ToString(dateformatted));
However, the output from this is
01/10/2017 1:13:00 PM
Which is 2 hours ahead of the actual time of 11:13:00. How can I convert the string to the proper timezone time?

I believe you are looking for the Parse(String, IFormatProvider, DateTimeStyles) overload of the Parse method. The third parameter, DateTimeStyles, will allow for force or prohibit conversion between local and UTC times. Options include: AdjustToUniversal, AssumeLocal, and AssumeUniversal (among others).

According MSDN docs:
Return value Type: DateTime
An object that is equivalent to the date and time contained in s.
Generally, the Parse method returns a DateTime object whose Kind
property is DateTimeKind.Unspecified. However, the Parse method
may also perform time zone conversion and set the value of the Kind
property differently,depending on the values of the s and styles
parameters:
If:
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| If | Time zone conversion | Kind property |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains time zone information. | The date and time is converted to the time in the local time zone. | DateTimeKind.Local |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains time zone information, and styles includes the AdjustToUniversalflag. | The date and time is converted to Coordinated Universal Time (UTC). | DateTimeKind.Utc |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains the Z or GMT time zone designator, and styles includes the RoundtripKind flag. | The date and time are interpreted as UTC. | DateTimeKind.Utc |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
You should add timezone.

Related

is there any way to parse a date in jq which contains milliseconds, or is there a way to get the interval between two dates without parsing?

So basically i need to get an interval between 2 dates and i have found how to do that using mktime, then deducting the two numbers.
But from my searching in the strptime c library, there doesnt seem to be a way to parse a date containing milliseconds, so im asking if there is any way around this, or if there is any way to parse a date containing milliseconds.
Edit: if there is any way to round up or down the date, or just remove the milliseconds that would work too
example:
{
"ActiveFrom": "2022-02-13T11:32:01.321345+04:00",
"ActiveTo": "2022-02-13T11:33:13.031743+04:00"
}
You could strip the fractional seconds with a substitution, and then go via strptime (required because of non-UTC timezone) to get a Unix timestamp:
echo '{
"ActiveFrom": "2022-02-13T11:32:01.321345+04:00",
"ActiveTo": "2022-02-13T11:33:13.031743+04:00"
}' \
| jq '.ActiveFrom
| sub("\\.[[:digit:]]+"; "")
| strptime("%Y-%m-%dT%H:%M:%S%z")
| mktime'
resulting in 1644751921 (jq playground).
If your dates are of OBJECT data type, you can easily calculate the interval like this:
var interval = date_later - date_early;

Why is the conversion from EST to UTC +5 hours and not +4? [duplicate]

This question already has answers here:
How to make a timezone aware datetime object
(15 answers)
Closed 6 years ago.
I've got a datetime which has no timezone information. I'm now getting the timezone info and would like to add the timezone into the existed datetime instance, how can I do?
d = datetime.datetime.now()
tz = pytz.timezone('Asia/Taipei')
How to add the timezone info tz into datetime a
Use tz.localize(d) to localize the instance. From the documentation:
The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
If you don't use tz.localize(), but use datetime.replace(), chances are that a historical offset is used instead; tz.localize() will pick the right offset in effect for the given date. The US Eastern timezone DST start and end dates have changed over time, for example.
When you try to localize a datetime value that is ambiguous because it straddles the transition period from summer to winter time or vice-versa, the timezone will be consulted to see if the resulting datetime object should have .dst() return True or False. You can override the default for the timezone with the is_dst keyword argument for .localize():
dt = tz.localize(naive, is_dst=True)
or even switch off the choice altogether by setting is_dst=None. In that case, or in the rare cases there is no default set for a timezone, an ambiguous datetime value would lead to a AmbiguousTimeError exception being raised. The is_dst flag is only consulted for datetime values that are ambiguous and is ignored otherwise.
To go back the other way, turn a timezone-aware object back to a naive object, use .replace(tzinfo=None):
naivedt = awaredt.replace(tzinfo=None)
If you know that your original datetime was "measured" in the time zone you are trying to add to it, you could (but probably shouldn't) use replace rather than localize.
# d = datetime.datetime.now()
# tz = pytz.timezone('Asia/Taipei')
d = d.replace(tzinfo=tz)
I can imagine 2 times when this might make sense (the second one happened to me):
Your server locale is set to the incorrect time zone and you are trying to correct a datetime instance by making it aware of this incorrect timezone (and presumably later localizing it to the "correct" time zone so the values of now() match up to other times you are comparing it to (your watch, perhaps)
You want to "tag" a time instance (NOT a datetime) with a time zone (tzinfo) attribute so that attribute can be used later to form a full datetime instance.

How to customize `serverTimestamp()`?

I want to customise setTimestamp().
firebase.firestore.FieldValue.serverTimestamp()
Currently the output is like August 27, 2019 at 3:38:55 PM UTC+5:30. What to do if I want the result to be August 27, 2019 only ?
When a timestamp type field is written to Cloud Firestore, it is just storing a value that describes a moment in time that's the same for all people on earth. What you're seeing in the console is just format that the console is using to make that readable by people. The timezone is represented in your computer's configured timezone.
If you're reading that timestamp in your code and want to format it for display in your app, you'll need to use some date formatting library to make that easy. It looks like you might be using JavaScript, so consider using a library such as momentjs to help with that. You will likely have to convert the timestamp to a Date type object first.
Firebase will always set a timestamp in a consistent way.
A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.
As the output you have given has a timezone, I'm guessing this has been applied elsewhere in your code when generating a Date object.
With this date object it is easy enough to reformat to match your desired display. An easy way if you are using angular is to use the date pipe
{{ dateObj | date }} // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }} // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }} // output is '43:11'
In your template you can call .toDate() method of your timestamp field. Do something like:
{{response.data().updatedAt.toDate() | date}}
The date pipe supports multiple formats:
{{response.data().updatedAt.toDate() | date:'short'}}
{{response.data().updatedAt.toDate() | date:'long'}}
...
See datePipe documentation.

TeradataSQL: Time to String, Add to Date and Compare to Another Time and Data

I'm trying to figure out the cleanest way to do a comparison in Teradata SQL Assistant. I have the scheduled start date (TimeStamp), the Schedule start time (varchar), actual start and end times (TimeStamp). I need to consolidate the scheduled start date and time and be able to compare it to the actual start and end date and time without modifying the original data (because it's not mine). I realize that the Scheduled Start Time [SST] is in a 24 hour time format with a AM/PM suffix, but like I said before, I can't change that.
I tried to do select cast(substr(scheduled_start_date,1,5) as TIMESTAMP(0)) from DB.TBL but am getting the "Invalid timestamp" error. There is example table data below.
Sch Start Date Sch Start Time Actual Start Actual End
09/11/2017 00:00:00 11:30 AM 09/11/2017 11:34:16 09/11/2017 11:58:00
05/26/2017 00:00:00 15:30 PM 05/26/2017 15:40:00 05/26/2017 15:55:15
11/06/2017 00:00:00 19:30 PM 11/06/2017 21:25:00 11/06/2017 21:45:00
Thanks!
You need to cast the schedule start time as an Interval, then you can easily add it to the start date:
scheduled_start_date
+ Cast(Substr(scheduled_start_time, 1,5) AS INTERVAL HOUR TO MINUTE)
A start date which is a timestamp seems to indicate this was ported from Oracle/SQL Server?
And a 24 hour time format with a AM/PM suffix is also quite strange.
A couple things to try:
Convert the separate Scheduled Date and Scheduled Time fields into strings, concatenate them, and feed that into a TIMESTAMP CAST. Something like:
SELECT
CAST(CAST(Scheduled_Date AS DATE) AS VARCHAR(25)) AS Date_String,
CAST(CAST(Scheduled_Time AS TIME FORMAT 'HH:MM BB') AS VARCHAR(25)) AS Time_String,
CAST(TRIM(Date_String) || ' ' || TRIM(Time_String) AS TIMESTAMP(0)) AS MyTimestamp
Cast the Scheduled Time field as a TIME data type. Cast the Scheduled Date field as a DATE data type. Then somehow combine the two into a TIMESTAMP field -- either with a CAST or some kind of timestamp constructor function (not sure if this is possible)
Option 1 should work for sure as long as you properly format the strings. Try to avoid using SUBSTRING and instead use FORMAT to cast as DATE/TIME fields. Not sure about Option 2. Take a look at these link for how to format DATE/TIME fields using the FORMAT clause:
https://www.info.teradata.com/HTMLPubs/DB_TTU_16_00/index.html#page/SQL_Reference%2FB035-1143-160K%2Fmuq1472241377538.html%23wwID0EPHKR
https://www.info.teradata.com/HTMLPubs/DB_TTU_16_00/index.html#page/SQL_Reference/B035-1143-160K/cmy1472241389785.html
Sorry, I don't have access to a TD system to test it out. Let me know if you have any luck.

Convert string to seconds - Robot framework

I am getting a time stamp from a page using:
|| ${value}= | Get Text | //span[#class='time']
it is returning a value in this format "Apr 28, 2015 03:03 AM AST". I want to convert it to seconds so that I can compare the time stamp with another event that has occurred previously in my test cases.
For previous event I have used the following and I am getting results in seconds:
|| ${secs} = | Get Time | epoch
Please let me know which info I am missing in above and I will edit my question. I would also appreciate if you can also guide me that after having the two stamps how can I tell if the difference of the two time stamps is less than 5 minutes or not.
You can use the DateTime library
The library has a convert date keyword that can convert into epoch time.
Note however, that once time-zones come into play, your tests would probably break down, Simply because someone ran it on a host in a different timezone.
*** Settings ***
Library DateTime
*** Keywords ***
Convert The date to epoch
[arguments] ${date}
${epoch_date}= Convert Date ${date} epoch
[return] ${epoch_date}
Convert date can also accept a format argument (Apr 28, 2015 03:03 AM AST)
${epoch_date}= Convert Date ${date} epoch date_format=%bbb %dd, %Y %H:%M %p %Z
The format is explained here:
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Resources