I'm trying to format a DateTime object to a String by using the Dates.format() function.
I'd like to get the week number for a specific time, however I can't find right formatting option in the docs.
I know I could get this by running Dates.week but I would really like to know if it's possible via format to have cleaner code (and crack a code golfing challenge...).
Here's some actual code:
julia> my_time = now()
2018-03-22T08:16:15.601
julia> Dates.week(my_time)
12
julia> Dates.format(my_time, "Y m d H:M:S")
"2018 3 22 8:16:15"
In R, I could do "%V" to get the weeks formatted. Is there a similar way in Julia?
No, there isn't a format specifier like %V:
julia> Base.Dates.CONVERSION_SPECIFIERS
Dict{Char,Type} with 12 entries:
'm' => Base.Dates.Month
'd' => Base.Dates.Day
'M' => Base.Dates.Minute
'Y' => Base.Dates.Year
'e' => Base.Dates.DayOfWeekToken
's' => Base.Dates.Millisecond
'U' => Base.Dates.Month
'E' => Base.Dates.DayOfWeekToken
'H' => Base.Dates.Hour
'y' => Base.Dates.Year
'u' => Base.Dates.Month
'S' => Base.Dates.Second
The in the code for these specifiers there's a note that there should be a way for packages to add more.
Related
I am trying to pull data (some transaction related data) from DB. To pull the data, I am passing start date and end date as an argument to the query.
Here I need to pull the data of last 2 months. i.e., Start time would be Jun 01, 2022 and End time would be Aug 01, 2022.
Below is the script:
#!/usr/bin/perl
use strict;
use warnings;
use DateTime;
use Date::Format;
use Date::Parse;
my $nowdate = DateTime->now(time_zone => 'local');
my ($month, $year) = ($nowdate->month, $nowdate->year);
my $date = DateTime->new(
year => $year,
month => $month,
day => 1,
);
my $end_time = str2time($date);
print "END:$end_time\n";
print time2str("%d-%m-%Y %T", $end_time)."\n"; #printing just to see in human readable format
my $start_time = $date->clone;
$start_time->add( months => 1 )->subtract( days => 92 );
$start_time = str2time($start_time);
print "START:$start_time\n";
print time2str("%d-%m-%Y %T", $start_time)."\n"; #printing just to see in human readable format
I have two issues over here:
I am using DateTime object two times to get end time. Can it be done in one shot?
$start_time->add( months => 1 )->subtract( days => 92 ); In this line of code, I have to explicitly mention subtract 92 days, which wouldn't be right always. Since some months have 30 days or 31 days or even 29 days. How can I get 2 month's beginning day date?
Another example: Lets assume if we are in September 2022, then Start time and End time would be Jul 01, 2022 and Sep 01, 2022 respectively.
Note: Perl version is 5.16.3
It would be good If I can do it with Core modules which comes with 5.16.3
You could simplify it by using truncate(to => 'month') to get to the first in the current month:
my $end = DateTime->now(time_zone => 'local')
->truncate(to => 'month');
This may however fail on a day without a midnight so this may be an option:
my $end = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->truncate(to => 'month');
Then subtract the number of months to get the start date:
my $start = $end->clone->subtract( months => 2 );
Then:
my $start_time = str2time($start);
my $end_time = str2time($end);
print "START:$start_time\n";
print time2str("%d-%m-%Y %T", $start_time)."\n";
print "END:$end_time\n";
print time2str("%d-%m-%Y %T", $end_time)."\n";
Possible output:
START:1654034400
01-06-2022 00:00:00
END:1659304800
01-08-2022 00:00:00
I need to convert a peculiar format of textual dates into dates in Julia. I found out about the MONTHTOVALUE dictionary in the Dates documentation, but this object is missing from the Dates namespace, gives no results in the help, and only appears in the Github source code in the documentation. I used Date.format() with formatting "U" to define my own MONTHTOVALUE:
# Build dictionary from month names to integers
MONTHTOVALUE = Dict{String, Integer}()
for i in 1:12
month = Dates.format(Date(1990, i, 1), "U")
MONTHTOVALUE[month] = i
end;
# Regular expression for date in the format [Month Year(Quarter)]
date_regex = r"(^[A-Z][a-z]*) ?(\d{4}) ?\((I*V?)\)";
function string_to_date(date_string)
month = MONTHTOVALUE[replace(date_string, date_regex, s"\1")]
year = parse(Int, replace(date_string, date_regex, s"\2"))
return Dates.Date(year, month, 1)
end;
#assert Dates.Date(1860, 10, 1) == string_to_date("October 1860(III)")
Does the MONTHTOVALUE dictionary exist already, or do you suggest a cleaner way?
If I understand the question correctly, you wish to access the dictionary inside the Dates module that maps month names to their number ("March"=>3, etc.), is that correct?
If so, Dates.LOCALES["english"].month_value seems to be the one you're looking for:
julia> Dates.LOCALES["english"].month_value
Dict{String,Int64} with 24 entries:
"January" => 1
"august" => 8
"May" => 5
"may" => 5
"December" => 12
"january" => 1
"August" => 8
"november" => 11
"december" => 12
"September" => 9
"july" => 7
"september" => 9
"October" => 10
"june" => 6
"November" => 11
"April" => 4
"February" => 2
"october" => 10
"March" => 3
"June" => 6
"april" => 4
"march" => 3
"february" => 2
"July" => 7
(There's also a Dates.LOCALES["english"].month_abbr_value if you need it.)
I'm guessing that part of the documentation is outdated, and MONTHTOVALUE used to be month_value dict's older name.
There's also the function Dates.monthname_to_value, used like Dates.monthname_to_value("September",Dates.LOCALES["english"]), providing an interface into the above dict.
I've not heard of Julia, but passage seems relevant:
Support for text-form month parsing is also supported through the u
and U characters, for abbreviated and full-length month names,
respectively. By default, only English month names are supported, so u
corresponds to "Jan", "Feb", "Mar", etc. And U corresponds to
"January", "February", "March", etc. Similar to other name=>value
mapping functions dayname() and monthname(), custom locales can be
loaded by passing in the locale=>Dict{String,Int} mapping to the
MONTHTOVALUEABBR and MONTHTOVALUE dicts for abbreviated and full-name
month names, respectively.
https://docs.julialang.org/en/v0.6.2/manual/dates/
Edit: I think you can make the dictionary like this:
monthtovalue = Dict{UTF8String, Int}()
for (value, name) in VALUETOMONTH[locale::AbstractString="english"]
monthtovalue[lowercase(name)] = value
end
Group rows by day/week/month using inserted_at column.
Example : If first row is created before 1 week then group by days and if any data is not created in middle date then add o as value.
[
{"21 Jul" => 12},{"22 Jul" => 0},{"23 Jul" => 3}, {"24 Jul" => 1}...
{"5 Aug" => 0}
]
Thanks in advance.
Let's suppose you have Event schema with DateTime field called starts_at.
To get, for example, events count by date you can make such function:
def get_events_count_grouped_by_date(query) do
query
|> group_by([e], fragment("date(?)", e.starts_at))
|> select([e], %{date: fragment("date(?)", e.starts_at), count: count(e.id)})
|> order_by([e], asc: fragment("date(?)", e.starts_at))
end
Then use it like this:
Event |> get_events_count_grouped_by_date() |> Repo.all()
It's not quite clear from the question exactly what is required, but hopefully the following query helps: It will give you the count of records grouped by the date part of inserted_at.
defmodule CountByDateQuery do
import Ecto.Query
#doc "to_char function for formatting datetime as dd MON YYYY"
defmacro to_char(field, format) do
quote do
fragment("to_char(?, ?)", unquote(field), unquote(format))
end
end
#doc "Builds a query with row counts per inserted_at date"
def row_counts_by_date do
from record in SomeTable,
group_by: to_char(record.inserted_at, "dd Mon YYYY"),
select: {to_char(record.inserted_at, "dd Mon YYYY"), count(record.id)}
end
end
Usage:
row_counts_by_date() |> Repo.all() |> Map.new()
%{"05 Aug 2017" => 2}
As stated in the title, I am attempting to get association rules for a dataset I am working with.
Unfortunately, the output is 388 rules likes this:
# lhs rhs support confidence lift
#[1] {} => {2760500500} 0.0005037281 0.0005037281 1
#[2] {} => {2638361901} 0.0005037281 0.0005037281 1
#[3] {} => {2810128001} 0.0005037281 0.0005037281 1
#[4] {} => {2217240500} 0.0005084802 0.0005084802 1
Is this a problem with the code or possibly the dataset I am using? Thanks.
EDIT: in the read.transactions function I used the parameter = list(minlen=2) to prevent this for future reference.
What characters are valid for use in SCSS variable names?
If you check out the source for the SASS lexer, you'll see:
# A hash of regular expressions that are used for tokenizing.
REGULAR_EXPRESSIONS = {
:whitespace => /\s+/,
:comment => COMMENT,
:single_line_comment => SINGLE_LINE_COMMENT,
:variable => /(\$)(#{IDENT})/,
:ident => /(#{IDENT})(\()?/,
:number => /(-)?(?:(\d*\.\d+)|(\d+))([a-zA-Z%]+)?/,
:color => HEXCOLOR,
:bool => /(true|false)\b/,
:null => /null\b/,
:ident_op => %r{(#{Regexp.union(*IDENT_OP_NAMES.map{|s| Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")})})},
:op => %r{(#{Regexp.union(*OP_NAMES)})},
}
Which references the IDENT character set defined in a separate file:
s = if Sass::Util.ruby1_8?
'\200-\377'
elsif Sass::Util.macruby?
'\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF'
else
'\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
end
H = /[0-9a-fA-F]/
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
NONASCII = /[#{s}]/
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
IDENT = /-?#{NMSTART}#{NMCHAR}*/
So, it looks like variable names can contain:
Any ASCII letter.
Any number 0-9 (as long as it is not the first character in the name).
Underscores and hyphens.
ASCII punctuation (!"#$%&'()*+,./:;<=>?#[]^{|}~) and spaces, if escaped with a backslash.
Unicode characters in the ranges 0080-D7FF, E000-FFFD, or 10000-10FFFF.
Unicode hex escape sequences such as \00E4.