Error Date and time odoo v8 - time

When I print my report I always get the time wrong (-1 hour), and I don't know how to solve this problem.
I have this function in my code :
def _interpolation_dict(self):
t = time.localtime() # Actually, the server is always in UTC.
return {
'year': time.strftime('%Y', t),
'month': time.strftime('%m', t),
'day': time.strftime('%d', t),
'y': time.strftime('%y', t),
'doy': time.strftime('%j', t),
'woy': time.strftime('%W', t),
'weekday': time.strftime('%w', t),
'h24': time.strftime('%H', t),
'h12': time.strftime('%I', t),
'min': time.strftime('%M', t),
'sec': time.strftime('%S', t),
}

You need to convert UTC timezone to User Timezone
You can do it using following method.
from datetime import datetime
import pytz
time_zone=self.env.user.tz
if time_zone:
local_now = datetime.now(pytz.timezone(time_zone))
else:
local_now=datetime.now()
return {
'year': local_now.strftime('%Y'),
'month': local_now.strftime('%m'),
'day': local_now.strftime('%d'),
'y': local_now.strftime('%y'),
'doy': local_now.strftime('%j'),
'woy': local_now.strftime('%W'),
'weekday': local_now.strftime('%w'),
'h24': local_now.strftime('%H'),
'h12': local_now.strftime('%I'),
'min': local_now.strftime('%M'),
'sec': local_now.strftime('%S'),
}
In above method we have get UTC time zone using datetime.now()
after that convert UTC timezone into User time zone using pytz
function.
This may help you.

Related

date-fns MMMM formatting is broken in Russian locale

Lets assume we have the following date: 2019, 11, 1.
I want to display only the month's name, but MMMM formatting results into "ноября", when I expect to get "ноябрь".
It works OK in moment.js (locale: ru):
// if format starts with month name
moment([2019, 11, 1]).format('MMMM') => 'ноябрь'
// if format doesn't start with month name
moment([2019, 11, 1]).format('DD MMMM') => '1 ноября'
I would like to switch to moment.js, although I am already utilizing the library which strictly depends on date-fns. How can I achieve the format to show the month's name correctly in Russian language?
date-fns's GitHub repo
My workaround for this problem in use case for react-datepicker was to pass month name in cyrilic as format.
const getMonthName = (date) => {
const months = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
return months[date.getMonth()];
};
<DatePicker dateFormatCalendar={ getMonthName(new Date()) } />
format(new Date(2014, 1, 11), getMonthName(new Date(2014, 1, 11)))
Worked under my limited use case
You need to change MMMM to LLLL

Check that Instant now happens during the java.time.Period / Duration

My intent is to set a condition to true only during a period.
The java.time.* API looked what I need.
import java.time.Period
import java.time.LocalTime
import java.time.Instant
import java.time.Duration
// java.time.Period
LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
Period period = Period.between(startDate, endDate);
// java.time.duration
Instant start = Instant.parse("2017-10-03T10:15:30.00Z")
Instant end = Instant.parse("2019-10-03T10:16:30.00Z")
Duration duration = Duration.between(start, end)
Instant now = Instant.now();
How to check that now is happening during the defined Period / Duration ?
I see no direct API.
Edit :
I found a way with java.time.Instant
// now, start and end are defined above
// if now is between start and end
if (now.isAfter(start) && now.isBefore(end)){
}
You are mistaken about what Period and Duration are.
They are distances (subtract beginning from ending). Period between 01/03/2018 and 01/10/2018 is exactly the same as in between 05/04/1990 and 05/11/1990, same thing for Duration. So that means nothing to ask something like "is 3rd january, 2018 in 3 months?"
First: a simple solution:
LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
LocalTime now = LocalTime.now()
boolean nowIsInTimeWindow = !(now.isBefore(start) || now.isAfter(end));
The same pattern works with LocalDate and LocalDateTime.
Second: additional thoughts on your original post:
now will never happen "during" period or duration. Both are just amounts of time, like "two days" or "five minutes". They don't contain information about start or end.
I'd suggest to not mix Instant and LocalDate but to use LocalTime instead of Instant. Thus you're consistent with regard to timezone: The Local... types are by definition timezone agnostic.

UTC to local method in DateTimeZone of Joda-Time to Java 8

We are changing Joda-Time API's to Java 8 time API's. In Joda-Time I have used:
DateTimeZone.convertLocalToUTC(this.getMillis(), true);
DateTimeZone.convertUTCToLocal(long millis);
Can any one tell me equivalent methods in Java 8?
Edited
convertLocalToUTC
DateTimeZone dateTimeZone = DateTimeZone.getDefault();
DateTime jodadatetime = new DateTime();
long utcTime = dateTimeZone.convertLocalToUTC(jodadatetime .getMillis(), true);
System.out.println(jodadatetime);
DateTimeZone dateTimeZone1 = DateTimeZone.UTC;
System.out.println(new DateTime(utcTime, dateTimeZone1));
Output
2017-08-09T17:27:57.508+05:30
2017-08-09T06:27:57.508Z
ConvertUtcToLocal
long utctolocal = dateTimeZone.convertUTCToLocal(jodadatetime.getMillis());
System.out.println("utc to local : " + new DateTime(utctolocal, dateTimeZone1));
Output
2017-08-09T17:27:57.508Z
So, your original date is 2017-08-09T17:27:57.508+05:30, then you want 2 things:
convertLocalToUTC: get 2017-08-09T06:27:57.508Z. This is a little bit tricky:
The original date is 2017-08-09T17:27:57.508+05:30, which is equivalent in UTC to 2017-08-09T11:57:57.508Z. What this method does is to convert this to the same local date and time but at the Calcutta timezone, and then you're printing it in UTC. In short:
original date is 2017-08-09T17:27:57.508+05:30
in UTC, that's the same as 2017-08-09T11:57:57.508Z
convertLocalToUTC converts this to 2017-08-09T11:57:57.508+05:30 (same date and time, but in Calcutta timezone)
and that's the same as 2017-08-09T06:27:57.508Z
To do this in Java 8, you can do:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
Instant i = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZoneSameInstant(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(i.toEpochMilli() + "=" + i);
Output:
1502260077508=2017-08-09T06:27:57.508Z
convertUTCToLocal: get 2017-08-09T17:27:57.508Z - the same date (2017-08-09) and time (17:27:57.508) but in UTC.
It's similar:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
ZonedDateTime z = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZoneSameInstant(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(z.toInstant().toEpochMilli() + "=" + z);
Output:
1502299677508=2017-08-09T17:27:57.508Z
You can also get the dates from the millis value.
For case 1:
// millis for original joda date: jodadatetime.getMillis() (1502279877508 = 2017-08-09T17:27:57.508+05:30)
long millisFromJoda = 1502279877508L;
Instant instant = Instant.ofEpochMilli(millisFromJoda)
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZone(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(instant.toEpochMilli() + "=" + instant);
Output:
1502260077508=2017-08-09T06:27:57.508Z
You can convert the Instant to another types if you want:
// convert to ZonedDateTime in UTC
ZonedDateTime zd = instant.atZone(ZoneOffset.UTC);
// convert to OffsetDateTime in UTC
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
Both will be 2017-08-09T06:27:57.508Z.
And for case 2:
ZonedDateTime zdt = Instant.ofEpochMilli(millisFromJoda)
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZone(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(zdt.toInstant().toEpochMilli() + "=" + zdt);
Output:
1502299677508=2017-08-09T17:27:57.508Z
Here is some code snippet that may help you get started:
LocalDateTime yourLocalTime = ...
long utc = yourLocalTime.toInstant(ZoneOffset.UTC).toEpochMilli();
or as you used strict = true the following:
long utc = ZonedDateTime.ofStrict(yourLocalTime, ZoneOffset.UTC, ZoneId.of("Z")).toInstant().toEpochMilli();
Converting back is similar:
LocalDateTime yourUtcTime = ...
long localTimeInMillis = yourUtcTime.toInstant(OffsetDateTime.now().getOffset() /* or: yourLocalTime.getOffset() */).toEpochMilli();
If you don't need the millis, but want to work with the DateTime-classes instead, you may want to use ZonedDateTime instead?
Creating a LocalDateTime from millis could be done as follows:
LocalDateTime yourLocalDateTime = Instant.ofEpochMilli(millisAsLong).atZone(/* your desired zone here */).toLocalDateTime();
where zone id could be ZoneId.of("Z"), ZoneId.systemDefault(), etc.

Ruby: How to check if date and time are within a range

I'm trying to create a method to determine whether or not a particular date and time (within a certain timezone) are within a range.
range = between(start_time, end_time)
start_time = "date time timezone"
end_time = "date time timezone"
Here's an example of what the range input will look like:
range => between("2013-12-25 04:45:00 -0800", "2015-12-25 5:00:01 -0800")
I want to return true or false if a particular date and time falls within this range.
Example particular date:
instance = "2014-01-01 16:35:45 -0800"
instance.between("2013-12-25 04:45:00 -0800", "2015-12-25 5:00:01 -0800")
I don't have much experience with time in Ruby. Any suggestions would be greatly appreciated.
require "date"
instance = DateTime.parse("2014-01-01 16:35:45 -0800")
d1 = DateTime.parse("2013-12-25 04:45:00 -0800")
d2 = DateTime.parse("2015-12-25 5:00:01 -0800")
p instance.between?( d1, d2 ) # => true

"strptime" in SWI-Prolog

How to convert atom '2015-12-15T05 PST' to timestamp or datetime?
I've tried parse_time/3
?- parse_time('2015-12-15T05 PST', '%Y-%m-%dT%H %Z', Stamp)
false.
and format_time/3
?- format_time('2015-12-15T05 PST', '%Y-%m-%dT%H %Z', date(Y,M,D,H,M,S,O,TZ,DST)).
ERROR: format_time/3: Arguments are not sufficiently instantiated
According to the documentation, the mode of format_time/3 can't really help you, because it's expecting everything to be passed in:
format_time(+Out, +Format, +StampOrDateTime)
This means you supply each of the arguments. You want to see something with a - prefix which means it's handing something back, which seems like it would mean parse_time/3, but there the documentation says:
Supported formats for Text are in the table below.
and it then proceeds to list exactly two options, rfc_1123 and iso_8601, neither of which really match your format. There does not seem to be a way to supply a format code here, which I find really puzzling, because there are underlying Unix libraries here that can certainly do this.
However, the problem can be solved with everyone's favorite tool: definite clause grammars! Here's my solution:
:- use_module(library(dcg/basics)).
myformat(date(Y,M,D,H,_,_,_,TZ,_)) -->
integer(Y), "-", integer(M), "-", integer(D),
"T", integer(H), " ", timezone(TZ).
timezone('UTC') --> "UTC".
timezone('UTC') --> "GMT".
timezone(-18000) --> "PST".
timezone(Secs) -->
[Sign], digit(H0), digit(H1), digit(M0), digit(M1),
{
(Sign = 0'+ ; Sign = 0'-),
number_codes(Hour, [H0,H1]),
number_codes(Minutes, [M0, M1]),
(Sign = 0'+
-> Secs is Hour * 3600 + Minutes * 60
; Secs is -(Hour * 3600 + Minutes * 60))
}.
my_time_parse(Atom, Date) :-
atom_codes(Atom, Codes),
phrase(myformat(Date), Codes).
I'm sure the learned will see ways to improve this code but it did the trick for me with your sample data. You will unfortunately need to either enumerate timezones or find a better source of data on them (perhaps parsing the system timezone definitions?) but if you know a-priori that you only need to handle PST, you can try it. Here's an example:
?- my_time_parse('2015-12-15T05 PST', Date).
Date = date(2015, 12, 15, 5, _G3204, _G3205, _G3206, -18000, _G3208) ;
false.
Hope this helps!
Coming late to this question: the desired format is close to iso_8601, which would take the format "2015-12-15T05-08". To replace the time zone " PST" with "-08", we can use append. For code:
:- set_prolog_flag(double_quotes, chars).
timezone(" PST", "-08").
timezone(" PDT", "-07").
%% etc
convert_time(Date, Stamp) :-
timezone(Zone, Delta),
append(Front, Zone, Date),
append(Front, Delta, Date2),
string_chars(Date3, Date2),
parse_time(Date3, iso_8601, Stamp).
test :-
convert_time("2015-12-15T05 PST", Stamp),
writeln('Stamp'=Stamp),
fail.
with output
?- test.
Stamp=1450184400.0
false.

Resources