I'm retrieving time from a Postgres DB.
Let's say it is:
2020-02-27 08:57:36.774147+00
Now I wanna write it in output like a string and I do it like this:
var myTime time.Time
fmt.Println(myTime.String())
In output it writes something different:
2020-02-27 08:57:36.774147 +0000 +0000
I need that value to be the same because I need to query something else with it.
Maybe the same issue is described here: https://github.com/golang/go/issues/11712
The function you need is time.Format. Replace "myTime.String()" with "myTime.Format(layout)" with a desired layout as the argument (e.g. the predefined "time.RFC3339" or a reference time format "2006-01-02 15:04:05.000000-07").
go doc:
func (t Time) Format(layout string) string
Format returns a textual representation of the time value formatted
according to layout, which defines the format by showing how the reference
time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the
desired output. The same display rules will then be applied to the time
value.
A fractional second is represented by adding a period and zeros to the end
of the seconds section of layout string, as in "15:04:05.000" to format a
time stamp with millisecond precision.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and
convenient representations of the reference time. For more information about
the formats and the definition of the reference time, see the documentation
for ANSIC and the other constants defined by this package.
Related
In Microsoft Graph Todo Task Item documents (this link) there are two fields with two different names but with the same description: lastModifiedDateTime and bodyLastModifiedDateTime.
Anyone knows the difference of these 2 fields?
You are right, the description on create todoTask is wrong.
If you check todotask resource's properties the bodyLastModifiedDateTime has the correct description.
The date and time when the task body was last modified. By default, it
is in UTC. You can provide a custom time zone in the request header.
The property value uses ISO 8601 format and is always in UTC time. For
example, midnight UTC on Jan 1, 2020 would look like this:
'2020-01-01T00:00:00Z'.
I have a lambda function that needs to store an item in a DynamoDB table that is going to be used by AppSync. I want to add a createdAt and a updatedAt field to the item, as AWSDateTime types, and set them to the time of their creation. As explained here I need to use An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. I use:
import datetime from datetime
datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
but what it gives me is something like 2022-03-26T18:23:47Z instead of 2022-03-26T18:23:47.210Z for example (The three number-places after the second are absent).
Could you please help me fix this?
Milliseconds are optional. Reduced precision formats are valid ISO 8601 timestamps and thus valid AWSDateTime types.
If milliseconds are meaningful to your use case, there are several ways to add them:
datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
datetime.now().isoformat(timespec='milliseconds') + 'Z'
# '2022-03-27T11:05:10.351Z'
I'm trying to parse this String into a ZonedDateTime:
"Mon 14 Aug 2017 02:00 AM CEST"
Here my last try:
System.out.println("Test ZonedDateTime: " + ZonedDateTime.parse(
"Mon 14 Aug 2017 02:00 AM CEST",
DateTimeFormatter.ofPattern("EEEE dd M yyyy KK:mm a z")));
And the response:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon 14 Aug 2017 02:00 AM CEST' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at be.hypertux.test.localtime.Main.main(Main.java:17)
Any ideas?
One problem is that short timezone names like CEST and CET are ambiguous and not standard. The ideal is to use IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
I'm assuming that CEST is the Central Europe Summer Time, which is used by lots of different countries (that's why it's ambiguous: you can't know which country or region it is, because it's a too broad range).
Although most abbreviations are not recognized (due to its ambiguity), some "defaults" are assumed for retro-compatibility reasons. In the version I'm using (JDK 1.8.0_131), it defaults to Europe/Paris, but not sure if that's what you need. And it's not guaranteed to work for all abbreviations. In this case, you can define a preferred timezone to be used (and that will an arbitrary choice, but there's no other way since CEST is ambiguous).
Another problem is that the month and day of week are in English (Aug and Mon), and you didn't specify a java.util.Locale. In this case, the DateTimeFormatter takes the system's default locale (and it's probably not English - check the value of Locale.getDefault()). Anyway, the default locale can be changed without notice, even at runtime, so it's better to specify one when you're dealing with localized data (like month and day of week names).
So, you must specify a locale and define an arbitrary timezone as the preferred one to be used when an ambiguous name like CEST is found. For that, you can use a java.time.format.DateTimeFormatterBuilder, a set of preferred timezones and a java.time.format.TextStyle:
// create set of preferred timezones
Set<ZoneId> zones = new HashSet<>();
// my arbitrary choice for CEST
zones.add(ZoneId.of("Europe/Brussels"));
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// date and time
.appendPattern("EEE dd MMM yyyy hh:mm a ")
// timezone short name with custom set of preferred zones
.appendZoneText(TextStyle.SHORT, zones)
// create formatter (use English locale for month and day of week)
.toFormatter(Locale.ENGLISH);
String input = "Mon 14 Aug 2017 02:00 AM CEST";
System.out.println(ZonedDateTime.parse(input, formatter));
The output will be:
2017-08-14T02:00+02:00[Europe/Brussels]
Note that I used Europe/Brussels as the preferred timezone. You can check all the available zone names (and choose accordingly) with ZoneId.getAvailableZoneIds().
I'm using hh for the hours, which is the hour-clock-of-am-pm field (values from 1 to 12). But in your code you used KK, which is the hour-of-am-pm field (values from 0 to 11). Check which one is best for your case.
A timezone is the set of all different offsets that a region had, has and will have during its history, and the dates when Daylight Saving Time starts and ends, etc. If 2 regions had some difference in this history, they'll have different timezones (even though they use the same rules today).
Just because Paris and Brussels use the same rules today (CET and CEST), it doesn't mean it'll be like this forever (because timezones rules are defined by governments and laws and there's no guarantee that they won't be changed at any time in the future).
That's why you must define some specific timezone instead of relying on ambiguous short names (even though their use is common and widespread).
In order for your format string to work, your date would need to be formatted like so: Monday 14 8 2017 02:00 AM CEST
Take out an E and add a couple of Ms and that should do it.
I'm trying to format a date like this: [daynumber] [monthname] [fullyear]
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println(t.Format("1 January 2014"))
}
However this prints out "11 November 10110" instead of the correct date "29 November 2014".
What is the correct way to use Time.Format?
Try:
fmt.Println(t.Format("2 January 2006"))
From Time.Format()
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,
Mon Jan 2 15:04:05 -0700 MST 2006
The article "Parsing and formatting date/time in Go " adds:
The use of a mnemonic over obscure formatting codes I think reflects the pragmatism of Go’s developers and their focus on creating a language that makes its users more productive
Ironically, I have trouble remembering the exact values and order of that format template.
(Especially the day and month that I keep mixing up, being used to the dd-mm convention, as opposed to mm-dd).
I have a Ruby script which downloads YouTube Insight reports for specific videos within specific date ranges. It authorizes with ClientLogin, retrieves <entry> XML data for a video, and extracts from that data a URL which points to a CSV report:
http://insight.youtube.com/video-analytics/csvreports
?query={VIDEO_ID}
&type=v
&starttime=1315353600000
&endtime=1317772800000
&user_starttime=1317168000000
&user_endtime=1317772800000
®ion=world
&token={API_TOKEN}
&hl=en_US
The above URL works. However, I want a report for a specific date range, not the default range provided.
An Insight report query's requested date range is set in the user_starttime and user_endtime params. (In the above default case, it's 2011-09-27 through 2011-10-04.) The YouTube API docs say that you can specify your own date range (covering a span of up to 28 days) by substituting timestamps (in milliseconds) that represent the dates you want.
So, why does the following query 404?
http://insight.youtube.com/video-analytics/csvreports
?query={VIDEO_ID}
&type=v
&starttime=1315353600000
&endtime=1317772800000
&user_starttime=1307937600000
&user_endtime=1308110400000
®ion=world
&token={API_TOKEN}
&hl=en_US
The date range looks OK:
ruby > Time.at 1307937600
=> 2011-06-13 00:00:00 -0400
ruby > Time.at 1308110400
=> 2011-06-15 00:00:00 -0400
The fact that the "default" URL works indicates that I must be doing something wrong with these date values, but I can't figure out what. What am I overlooking?
UPDATE 2 -- Nov. 4, 2011:
There has recently been a change to the YouTube Data API Protocol for Insight data, and the answer below is no longer accurate.
YouTube now permits date ranges of up to 31 days for a single Insight report query, and they now allow requests pertaining to dates going back to March 1, 2009. The docs now say:
You can adjust the date range for which a report contains data
to a period of up to 31 days beginning no earlier than March 1, 2009.
This is excellent news. (Leaving the below for posterity.)
I believe I've figured out why the above Insight report query with the custom date range is 404ing. I was able to retrieve a report with a custom date range like this:
http://insight.youtube.com/video-analytics/csvreports
?query={VIDEO_ID}
&type=v
&starttime=1315353600000
&endtime=1317772800000
&user_starttime=1315627200000
&user_endtime=1315972800000
®ion=world
&token={API_TOKEN}
&hl=en_US
What's the difference between this (good) URL and the previous (bad) URL in my question above? Well, my custom date range here, specified in the user_starttime and user_endtime parameters both fall within the range set by YouTube in the starttime and endtime params.
In other words, starttime and endtime seem to represent the outer bounds of any user-specified custom date range possible through these types of requests.
So, when the YouTube API docs say:
You can adjust the date range for which a report contains data to a period of up to 28 days
What they mean, I suppose, is:
Your date range may not span more than 28 days ... AND ALSO ...
Your date range may not fall outside of a date range going back 28 days from the most recent date on which reports are currently available, which we tell you through the starttime and endtime parameters.
UPDATE:
In this thread, a YouTube API Team member says:
You should consider the starttime value the absolute earliest supported start date and endtime the absolute latest supported end date. If you try to set user_starttime to something earlier than starttime then you're going to ask for data that dates back more than 28 days, and that data isn't available.
This exact text should be in the documentation.