Rails 4.0.0 DateTime.strptime need 12 hour no-padding |
It seems to be parsing fine, using the %l option.
2:17 AM
> DateTime.strptime("8/13/2013 2:17 AM", "%m/%d/%Y %l:%M %p")
=> Tue, 13 Aug 2013 02:17:00 +0000
2:17 PM
> DateTime.strptime("8/13/2013 2:17 PM", "%m/%d/%Y %l:%M %p")
=> Tue, 13 Aug 2013 14:17:00 +0000
|
How to present Rails form datetime select in different time zone? |
There are a couple of options:
Utilize the user's local timezone when displaying data to them. This is
really easy with something like the browser-timezone-rails gem. See
https://github.com/kbaum/browser-timezone-rails. It is essentially
overriding the application timezone for each request based on the timezone
detected from the browser. NOTE: it only uses the OS timezone, so it's not
as accurate as an IP/geo based solution.
Setup your application timezone so that it is consistent with the majority
of your user base. For example: config.time_zone = 'Mountain Time (US &
Canada)'. This is a very standard thing to do in rails. Rails will always
store the data in the DB as UTC, but will present / load it using the
application timezone.
Create a timezone for your user model. Allow
|
add hour-minute to datetime |
you should check strtottime() documentation to add 1 hour simply use
strtotime("+1 hour");
you can also use time() + 60*60
There is also method in DateTime object called "add" that you can use.
From manual:
DateTime::add -- date_add — Adds an amount of days, months, years,
hours, minutes and seconds to a DateTime object
You can create DateInterval object and add the interval to exsiting
DateTime object.
To format date you can use format() method on DateTime object.
Edited:
Simple explode may solve your problem as well.
$interval="01:00";
$xp = explode(":", $interval);
$time=time() + (int)$xp[0] * 60*60 + (int)$xp[1]*60;
echo date("h:ia", $time);
Or more object oriented soution
$interval="01:00";
$now=new DateTime();
$now->add(new DateInterval("P0000-00-00T$inter
|
Datetime variable "tics" one hour |
A DateTime object has a Kind property. This property says whether the data
should be interpreted in UTC (DateTimeKind.Utc) or in the local time zone
(DateTimeKind.Local), or whether it is unknown (DateTimeKind.Unspecified).
You should use the overload of DateTimeParse that takes a DateTimeStyles
parameter, and specify DateTimeStyles.AssumeUniversal or
DateTimeStyles.AssumeLocal.
|
C# get whole hour values between 2 datetime objects |
The following will return the total hours between the 2 DateTime objects:
(datevalue1 - datevalue2).TotalHours
And for a custom behavior,such as displaying a list of hours, use a simple
custom method on that Timespan created to get a list of hours in your
desired format.
Code suggestion of the top of my head:
public List<String> GenerateHours(DateTime t1,DateTime t2){
if ((t2-t1).TotalHours >24)){
//decide what to do.
return null;
}else{
var currentHour = t2.Hour;
var list = new List<String>();
for (int i=0;i<(t2-t1).TotalHours;i++){
if (currentHour<10){
list.Add("0"+currentHour+":00");
}else if (currentHour>=10){
list.Add(currentHour+":00");
}
|
How to move the datetime to end of day, week or hour |
I agree with Andy; that can't be the intended behavior of shift. A cleaner
way to shift times to the end of the month is this:
from pandas.tseries.offsets import MonthEnd
times = Series(times)
times.map(lambda x: x + MonthEnd())
But there is no such thing as HourEnd, DayEnd, or WeekEnd. For those cases,
how about following this pattern?
from pandas.tseries.offsets import Second, Minute, Hour, Day
times.map(lambda x: x + Minute(59-x.minute) + Second(59-x.second))
times.map(lambda x: x + Hour(23-x.hour) + Minute(59-x.minute) +
Second(59-x.second))
times.map(lambda x: x + Day(6-x.weekday()) + Hour(23-x.hour) +
Minute(59-x.minute) + Second(59-x.second))
If you want the last day of the week but not necessarily the last second of
that day, then the expression is obviously sim
|
Extract Hour From "yyyymmddHH" |
Like @Klaus already commented, in this case a simple substr would to the
trick, i.e. substr('2013050100', 9, 10). Remember that substr is vectorized
so you can simply do:
df$Hour = substr(df$HourStamp, 9, 10)
A more flexible and powerful way of dealing with dates/times is to simply
convert HourStamp into a real R date object:
d = strptime('2013050100', format = '%Y%m%d%H')
strftime(d, '%H')
[1] "00"
In this case the strptime solution is a bit cumbersome, but it allows for
stuff like:
> strftime(d, '%A %d of %B in the year %Y')
[1] "Wednesday 01 of May in the year 2013"
or:
strftime(d, 'file%Y%d.csv')
[1] "file201301.csv"
or in vectorized form for your example:
df$time = strptime(df$HourStamp, format = '%Y%m%d%H')
df$Hour = strftime(df$time, '%H')
|
minus 1 hour to DateTime using Joda Time |
Just use:
dateTime.minusHours(1)
This is documented in the API.
Note that DateTime objects are immutable, so the operation alone has no
effect. You need to assign the result of this method to a new object (or
replace itself):
dateTime = dateTime.minusHours(1);
As to how to obtain a Period out of the difference between two DateTimes,
you must first go through an Interval:
Period period = new Interval(begin, end).toPeriod();
Link to a SO post explaining why there is both Period and Interval.
Side note: Joda Time uses a LOT of indirections in its API; as such reading
the Javadoc not only requires one to read the methods for one class, but
also look at the list of inherited methods from all the inherited abstract
classes/interfaces; for instance, a DateTime is also a ReadableInstant
|
extract a logs before one hour from log file |
You can try this,
grep " $(date --date='1 hour ago' '+%H').*MTS" /var/log/oss.log >
oss.new.log
Or
grep "s$(date --date='1 hour ago' '+%H').*MTS" /var/log/oss.log >
oss.new.log
|
Converting DateTime from specific timezone to UTC - missing hour? |
Yes there is a dalylight saving applied. See Wikipedia
Places that use Eastern Standard Time (EST) when observing standard
time (autumn/winter) are 5 hours behind Coordinated Universal Time
(UTC−05:00).
Eastern Daylight Time (EDT), when observing daylight saving time
(spring/summer) is 4 hours behind Coordinated Universal Time
(UTC−04:00).
The conversion method is correct. Your assumption about the EST timezone is
flawed. If your input dates are really EST then the conversion is correct.
If that does not meet your expectations you need to check from where your
input data comes from and in which timezone it was really entered.
If you are dealing with saved dates in a database and you do not know
anymore what is correct and what not you are in trouble.
In general it
|
datetime.date.fromtimestamp: ignores hour and minute |
You are creating date objects, not datetime. Dates ignore all time
information.
Use datetime objects instead if you want to preserve the time component:
>>> from datetime import datetime
>>> datetime.fromtimestamp(1339119900000/1e3).strftime('%Y-%m-%d
%H:%M')
'2012-06-08 02:45'
>>> datetime.fromtimestamp(1339120800000/1e3).strftime('%Y-%m-%d
%H:%M')
'2012-06-08 03:00'
|
Change to a 24 hour format for datetime data in Google Charts |
You need to format the datetimes using a DateFormatter.
// format dates
// ex: "August 5, 2013 1:45 PM" formatted as "05/08/2013 13:45"
var dateFormatter = new google.visualization.DateFormat({pattern:
'dd/MM/yyyy HH:mm'});
dateFormatter.format(data, 0);
You can format the axis labels by setting the hAxis.format option:
var options = {
hAxis: {
format: 'dd/MM/yyyy HH:mm'
}
title: 'price'
};
The date formats support most of the ISO date formatting patterns.
|
MVC : Binding datetime value (bootstrap datetime picker) from view to model |
You need to give the input tag a name that corresponds to a property in
your model, like this:
<input name="DateEntered" data-format="dd/MM/yyyy HH:mm:ss PP"
type="text"/>
|
rails select multiple array option,non model field validation |
To use validations you need a model. What you maybe need is a model that is
not backed in the DB. You can just:
include ActiveModel::Validations
in the model Class definition. Check this railscast:
http://railscasts.com/episodes/219-active-model
|
Rails Postgres - Datetime value won't save into Datetime column |
Try putting these in the create method:
logger.error params[:special_deal].class
logger.error params[:special_deal].to_datetime
or use the debugger to investigate them.
It seems that it doesn't get converted properly to datetime.
You will get a clear hint after this.
|
Rails 12 hour AM/PM range for a day |
I agree with @MrYoshi's comment, the easiest way of formatting a date is
.strftime(),
see RubyDoc for all possible options
Example:
Time.now.strftime("%I:%M %p")
output: HH:MM AM
Or what you literally asked for:
Time.now.strftime("%I:00")
output: HH:00
As you mentioned time_select I assume you want to offer time as a user
selectable range, so try these options for time_select(more options):
time_select 'game', 'game_time', {:minute_step => 60, :ampm => true}
also this previous question: Time select form helper with 12 hour format
for Rails 3?
|
Rails clean up folder every hour |
Write a CRON tab and execute it every hour. Something like
0 * * * * find /path/to/rails/public -name "*.txt" -mtime +1 | xargs rm -fr
Of course, replace *.txt with a pattern that matches your files.
Edit: @JoeFrambach has an issue with piping find to xargs but he doesnt
elaborate WHY or offer an alternative solution. If you didn't want to use
the pipe you can use the -exec switch with find:
find /path/to/rails/public -name "*.txt" -mtime +1 -exec rm {} ;
Which ultimately should be the same.
|
Hour logging rails application |
Assuming that you've declared the belongs_to and has_many relationships in
the models, and that the hours model includes the user_id foreign key
(t.references :users in the migration), and that the relationship from user
to hours is called hours, then you'd use something very close to this:
current_user.hours.create(params)
It starts with the current_user and traverses the assocoiation, which
causes the user_id to be set in the User record when you call create.
current_user is the Devise method for access to the User object for
whomever Devise thinks is logged in.
|
How do I convert a DateTime SELECT in Entity Framework 5 to only SELECT the date portion? |
Have you tried formatting the date?
airDate =
EntityFunctions.TruncateTime(schedules.DateSched).ToString("d",
CultureInfo.CreateSpecificCulture("en-US"))),
|
rails order by time with reversed 24 hour periods |
I guess you can do it like that
c = Event.where(:time_start > 12.hours).order(:time_start) <<
Event.where(:time_start < 12.hours).order(:time_start)
this will concatenate the two results one after the other and give you the
desired result.
|
How to extract only Time from a DateTime field in Oracle SQL Developer? |
Assuming your goal is to generate a string representing the time (which is
what the query you posted returns despite the extraneous to_number calls)
SELECT to_char( <<column_name>>, 'HH24:MI:SS' )
FROM table_name
If you want to return a different data type, you'd need to tell us what
data type you want to return. If, for example, you really want to return
an INTERVAL DAY TO SECOND
SELECT numtodsinterval( <<column name>> - trunc(<<column
name>>), 'day' )
FROM table_name
|
How to use UIDatePicker (countdown timer) to select 0 hour 0 minute? |
You can set date picker to 00 programmatically in viewDidLoad:
NSDateComponents * components = [cal
components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:date];
[components setHour:0];
[components setMinute:0];
[comps setSecond:0];
NSDate * date = [cal dateFromComponents:components];
[self.datePicker setDate:date animated:TRUE];
|
How to extract joda DateTime belonging to specific time range? |
List<DateTime> filtered = new ArrayList<>();
for (DateTime dt : mycollection){
if (dt.getHourOfDay >= 10 && dt.getHourOfDay <= 12){
if (dt.getHourOfDay != 12 ||
(dt.getHourOfDay == 12 && dt.getMinuteOfHour <=
30)){
filtered.add(dt);
}
}
}
|
Create a select list in half-hour increments in python |
If the times are in minutes, the following should work fine:
xrange(0, 1440, 30)
If they're supposed to be in some other format, this can generate them
fine, and then be converted to whatever format you want.
Ex:
[(str(i / 60) if i / 60 > 9 else "0" + str(i / 60)) + ":" + (str(i % 60)
if i % 60 > 9 else "0" + str(i % 60)) for i in xrange(0, 1440, 30)]
to give HH:MM
To get HH:MM[AM/PM], the following should work, if rather messily:
[((str(i / 60 % 12 + 1) if (i / 60 % 12 + 1) > 9 else "0" + str(i / 60 %
12 + 1)) + ":" + (str(i % 60) if i % 60 > 9 else "0" + str(i % 60)) +
("am" if i / 60 < 11 or i / 60 > 22 else "pm")) for i in xrange(0,
1440, 30)]
Edit: This will be in the right order, but won't start at the right place.
To solve that, if the list formed from
|
Automatically run a select statement against a remote mysql server over SH tunnel every 1 hour |
Here is a quick reference of how cron works. You can run MySQL script thru
.php.
To run it every one hour, you should do it like this:
* */01 * * * username /var/www/html/[phpFileYouWantToRun]
You can either include /usr/bin/php in the command to run, or you can make
the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which
interpreter to use:
#!/usr/bin/php
<?php
// your code here
Another solution is to make an scheduled jobs in MySQL directly like in
this link: "How to Create Scheduled Events in MySQL"
|
Converting JSON data 24 hour time to 12 hour with Javascript |
You can use momentjs to format the date in the way you prefer. Fist include
momentjs http://momentjs.com/ in your project, and then you will be able to
do:
moment('06-16-2013 16:00:00','MM-DD-YYYY HH:MM:SS').format('MM-DD-YYYY
hh:mm:ss a')
|
javascript time 24 hour to 12 hour with a click button |
The javascript Date when initialized using something like var currentDate =
new Date(); will hold the current date and time. You can then use the
currentDate.getHours() method to get the hours in 24 hour format.
Changing this to 12 hour format first involves checking whether the hour is
greater than or equal to 12 (in which case the suffix will be PM, otherwise
it will be AM). After this you just modulo the hours by 12.
The minutes and seconds can be retrieved using currentDate.getMinutes() and
currentDate.getSeconds() respectively.
Here is a fiddle that demonstrates the above.
|
Convert 12-hour time format to 24 hour integer? |
You can use DateTime.Parse(...) to get a DateTime value, and then reference
the .Hour property for a result;
int h = DateTime.Parse("10am").Hour; // == 10
int h2 = DateTime.Parse("10pm").Hour; // == 22
DateTime.Parse is pretty liberal in what it allows, but obviously makes
some assumptions internally. For example, in the above code,
DateTime.Parse("10am") returns 10am on the current date in the current
timezone (I think...). So, be aware of the context in which you use the
API.
|
Rails console return list of model if model's method returns false |
Vehicle.all.select(&:auto?)
Note that this is slow if there are a large number of vehicles, since they
will all be loaded into ruby. It's more efficient therefore to do the test
in SQL. E.g. if your #auto? method merely looks at an auto boolean field
you could do this instead:
Vehicle.where(auto: true)
That also has the advantage of getting the result as a Relation rather than
an Array, which allows you further refine the statement downstream before
calling the database.
|
Rails - AssociationTypeMismatch error with associating a model with multiple instances of another model |
original_account_id is expecting an account object. you cannot set an id.
credit_record.original_owner = account
credit_record.account = account
or
credit_record.account_id = account.id
Please rename your association to the following
class CreditRecord < ActiveRecord::Base
belongs_to :original_owner, :foreign_key => "account_id", :class_name
=> "Account"
belongs_to :account
|
DateTime model binding asp.net mvc |
The computer will parse the date based on its region (it is set in the
control panel in various places depending on the OS). If your two machines
have different regional settings, there will be friction as different
regions exress dates different (dd/mm/yyyy in the U.K., mm/dd/yyyy in the
U.S.). You can override that setting by configuring your web.config to help
with consistency.
<globalization culture="en-US" uiCulture="en-US"/>
Another option I would suggest is to save the value of your web form
control in the universal date time format: e.g. Tue, 1 Jan 2008 00:00:00
GMT. This will be parsed correctly irrespective of your machine's region.
|
Query data for hour by hour report |
SELECT DATEPART(hh, DateCreated) AS hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/14/2013' AND DateCreated < '6/15/2013'
GROUP BY DATEPART(hh, DateCreated)
Read more about DATEPART() here.
You can of course add more groupings for day, week, whatever you want:
SELECT DATEPART(dd, DateCreated) AS day, DATEPART(hh, DateCreated) AS hour,
sum(Units) Units
FROM orders
WHERE DateCreated >= '6/10/2013' AND DateCreated < '6/15/2013'
GROUP BY DATEPART(dd, DateCreated), DATEPART(hour, DateCreated)
|
The MVC model's datetime format always can't be control |
Have you tried this way,
@Html.TextBoxFor( model=>model.ClassDate, new { @readonly = "true",
style = "width:135px", type="date", @Value = Model.ClassDate.Day + "/" +
Model.ClassDate.Month + " / " + Model.ClassDate.Year})
I had the same problem but this really works for me....
|
Method in model which returns another has_many model in Rails 3.2 |
Sounds you should first do:
has_many :attributes, :through => :categories
Then it should simply be:
joins(:attributes).where(:attributes => { :is_key => true })
You could even define an association extension as such:
has_many :attributes, :through => :categories do
def is_key(value=true)
where(:is_key => value)
end
end
|
Asp.net MVC nullable DateTime model state validation |
you are doing the client side validation, then you dont worry about that
validation if the birth date value is null or empty then you returns null.
public class DateFieldAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (value == null || value == string.empty)
{
return null;
}
else
{
//Validate the Birth date.
}
}
}
If you return NULL then the Modelstate doesn't consider Birthdate field.
|
DateTime Selectlist from model to view to controller |
I would try something like this
@Html.DropDownListFor(x => x.RaceTime, new
SelectList(Model.TimeSlotOptions, "Id", "Name"), "-- Race time --")
instead of
@Html.DropDownListFor(model => model.RaceTime, Model.TimeSlotOptions,
"-- Race time --")
|
how to pass model with jquery ajax post with datetime |
Instead of passing datetime to controller you should pass it as a string,
and then parse into datetime in controller.
Make a string property that convert your datetime to string.
public string MyDateTimeString
{
get{ return datetime.toString();}
set{ datetime = Convert.toDateTime(value);}
}
|
Bulk convert log file date time format from 12 hour clock to 24 hour clock for mySQL database |
If you want to do that on db side and you use MySql you can read it with
STR_TO_DATE() and either use it as a datetime value
INSERT INTO log (`Site_Name`, `number_of_clicks`, `date`,
`Interaction_Type`)
SELECT 'site1', 10, STR_TO_DATE('10/05/2013_2:00PM', '%d/%m/%Y_%l:%i%p'),
1;
or
UPDATE log
SET date = STR_TO_DATE(str_date, '%d/%m/%Y_%l:%i%p');
assuming that date column is of type datetime, and str_date column contains
string values in 12h format.
or if for some reason you store it as VARCHAR and really need to format it
as DD/MM/YYYY_14:00 then you can use DATE_FORMAT()
DATE_FORMAT(STR_TO_DATE('10/05/2013_2:00PM', '%d/%m/%Y_%l:%i%p'),
'%d/%m/%Y_%k:%i')
which will produce
| NEWDATE |
--------------------
| 10/05/2013_14:00 |
To update in-place
UPDATE log
SET
|
Rails DateTime Comparison Bug |
Date is for, um, dates. Dates have a resolution of one day so there are no
hours, minutes, ... For example:
>> Date.parse('2013-08-07 16:35:38').strftime('%Y-%m-%d %H:%M:%S')
=> "2013-08-07 00:00:00"
That means that your current_time string has zeros for the hours, minutes,
and seconds. Perhaps you want to use a DateTime instead:
>> DateTime.parse('2013-08-07 16:35:38').strftime('%Y-%m-%d
%H:%M:%S')
=> "2013-08-07 16:35:38"
|
Django execute task on time specified in model datetime field |
If you're on a UNIX-like machine, it's possible that you have access to
cronjobs. If you're on Windows, I hear there's a program called at that can
do similar things. If this doesn't suit your needs, there are a number of
ways to do things every X hours using the time library
(time.sleep(SOME_NUMBER_OF_SECONDS) in a loop with whatever else you want
to do will do it if you want something done regularly, otherwise you'll
need to look at time.localtime() and check for conditions).
|