I have a field timestamp = models.DateTimeField(auto_now_add=True) in the db. I want to find the difference between that timestamp and datetime.now().
When I tried datetime.now() - timestamp, I get the error:
can't subtract offset-naive and offset-aware datetimes
How do I fix this?
This error refers to how times are stored by python. According to the python documentation:
There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment.
The django documentation also states that:
When time zone support is disabled, Django uses naive datetime objects
in local time. This is simple and sufficient for many use cases. In
this mode, to obtain the current time, you would write:
import datetime
now = datetime.datetime.now()
When time zone support is enabled,
Django uses time-zone-aware datetime objects. If your code creates
datetime objects, they should be aware too. In this mode, the example
above becomes:
import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
You should determine whether or not you want timezone awareness in your site and then adjust your stored times accordingly. To convert an aware dt to naive you can use the pytz module and do this:
naive_dt = aware_dt.replace(tzinfo=None)
This works because all python datetimes have an optional timezone attribute, tzinfo, which can be used to store information on the dt's offset from UTC time.
Holá
The short answer is:
tz_info = your_timezone_aware_variable.tzinfo
diff = datetime.datetime.now(tz_info) - your_timezone_aware_variable:
You must add the timezone info to your now() time.
But you must add the same timezone of the variable, thats why I first read the tzinfo attribute.
Related
As part of setting GCP project level timezone to AEST, I have run the following command -
ALTER PROJECT `gcp-abc-def`
SET OPTIONS ( `region-us.default_time_zone` = 'Australia/Sydney')
Doing so, I see that current_datetime() is getting changed to AEST whereas timestamp remains UTC, as can be seen below.
Can someone help how this can be remedied? What other settings to be changed?
I see that current_datetime() is getting changed to AEST whereas timestamp remains UTC this is because the current_timestamp function shows time in timestamp type. A timestamp does not have a time zone; it represents the same instant in time globally. When querying for CURRENT_TIMESTAMP() it shows explicitly in UTC by having zero time zone offset. When you convert a timestamp to some other type that isn't tied to a particular timezone, you can specify the timezone for the conversion.You can use format_timestamp to convert the timestamp into your zone specific time.
Example:
ALTER PROJECT `gcp-abc-def`
SET OPTIONS ( `region-us.default_time_zone` = 'Australia/Sydney');
select current_datetime() as cdt, current_timestamp() as cts,format_timestamp('%c',current_timestamp(),'Australia/Sydney') as cts2
I have a sqlite db (it is the spiceworks db) and I am mapping the tables to grails domain classes. There is a table in particular that is in a datetime format (yyyy-MM-dd HH:mm:ss). An example of such a date in the db for anyone who wants to verify would be: 2015-06-26 15:32:39
I created the domain class and mapped my properties to the columns. Let grails generate the views so that they are default. When I try to get to the index page I get:
URI
/spiceworks/weeklyReportItem
Class
java.text.ParseException
Message
Unparseable date: "2015-06-26 15:32:39" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
I've used MSSQL datetimes in the past and have never ran into this issue. In the database, the data type for the problematic column is datetime. Anyone know what's going on?
EDIT: I only have Read permissions on the db and the spiceworks source code isn't open source.
If you look at that regular expression, you'll see it's looking for a ISO8601 timestamp formatted like YYYY-MM-DD HH:mm:SS.SSS - in other words, it needs a decimal seconds, and you're just providing whole seconds.
An easy fix would be to update every existing value in the relevant column by appending '.000' to it, and update the insertion routines to do the same.
If you refer to the sqlite date time functions, there's a %f format specifier for strftime() that can be used to produce fractional seconds that might be helpful if you're building the timestamp directly in an insert query.
In the database, the data type for the problematic column is datetime
Sqlite3 doesn't have a datetime type. The timestamps you're storing are strings. More information.
I have a DateTime in my .NET program that I need to print with particular value of time zone offset (for instance, +01:00 always). Output should contain full date time with timezone. It has to be unrelated to system timezone setting. How I could achieve this?
Example: I have a timestamp such as 12-03-2016T12:30:34+03:00 and I need to output it calculated for predefined TZ +1: 12-03-2016T10:30:34+01:00
Found some approach to it.
First of all, DateTime does not have time zone stored in it. Instead it has flag whether it is UTC or Local (without the idea what Local TZ shift is). So: first thing is to get your initial parsing of time from any string time stamp in UTC.
Once it is stored in DateTime object (with Kind=UTC), you have to convert it to the timezone you desire output for. I find examples here useful: datetime to string with time zone.
Note: if you need to convert London daylight-saving time, you have to know right names of timezones in NET so you get it right. See Difference between UTC and GMT Standard Time in .NET
I know this question has been hashed over multiple times and I read lots of posts on that hashing but still am confused.
Using MVC4/WebAPI, I have a datetime that is simply created as new DateTime.Now.
My WebAPI is return data like this:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new
{
data = sessionRecordSmalls,
count = sessionRecordSmalls.Count,
success = true
});
where sessionRecordsSmall has a public property of DateTime in it.
When I look at the date in the VS debugger, it shows it as now with no timezone of course because DateTime does not include a timezone.
{10/6/2012 9:45:00 AM}
When I look at what gets downloaded from the server, I see in the JSON
2012-10-06T09:45:00
I think the T0 means Timezone 0, not 100% sure of that. My JavaScript library interprets it as timezone 0, then shows the actual date downloaded as GMT (-9 hours ago for me).
My question is, what is the JSON downloaded? Is that include a timezone? Am I missing some important step here?
if serializing with json.net keep in mind that you can specify DateTimeZoneHandling.
Example in WebApiConf.cs
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling =Newtonsoft.Json.DateTimeZoneHandling.Local;
The date time 2012-10-06T09:45:00, which we recive in JSON with Web API and default serializer is the ISO 8601 format.
In fact this is so called Combined date and time representations. Extract:
..A single point in time can be represented by concatenating a
complete date expression, the letter T as a delimiter, and a valid
time expression. For example "2007-04-05T14:30"...
There is no time zone information in this format. As mentioned in the Time zone designators Extract:
Time zones in ISO 8601 are represented as local time (with the
location unspecified), as UTC, or as an offset from UTC. If no UTC
relation information is given with a time representation, the time is
assumed to be in local time.
In other words, if there is no offset from UTC specified, it is treated as a local time.
The UTC format would be extended with Z at the end
If the time is in UTC, add a Z directly after the time without a
space. Z is the zone designator for the zero UTC offset. "09:30 UTC"
is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would
be "14:45:15Z" or "144515Z".
UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.
So, the date-time we recieve is the ISO 8601 format, treated as local time zone (no Z at the end like this 2012-10-06T09:45:00Z)
I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.
How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.
thank you
When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.
I belive that if you use SqlParameters ADO.NET will take care of the rest and you don't have to worry about it. Besides, it's good for defending against SQL Injection attacks too! :)
** Watch out because SQL DateTime columns are non-nullable and their minimum value is 1/1/1753 while .net DateTimes are non-nullable with min values of 1/1/0001. **
If you're pulling data from a real DateTime column, by default it will always be in the same standard format. For saving the data to the column, you might want to specify the SqlDbType.DateTime in your parameter.
i ripped this off of http://bytes.com/forum/thread767920.html :
com.Parameters.Add("#adate", SqlDbType.DateTime).Value = DateTime.Now;
Well, if you keep datetime fields in the DB you shouldn't worry about it.
As long as you keep the dates in app strongly typed (DateTime variables) and send the dates through prepared statements with DBParameter/SqlParameter your DB will take them as is.
If you use strings to hold your dates in code, some casts will ensure you send the right values:
string sqlCmd = #"SELECT *
FROM MyTable
WHERE MyDateField = CONVERT(datetime, '{0}', 101)";
// assuming myDateString is a string with a date in the local format
sqlCmd = string.Format(sqlCmd,
Convert.ToDateTime(myDateString).ToString("yyyyMMdd"));
(the code is ugly, but hopefully it gets the point across)
As others have mentioned, you should be OK as far as storing datetimes culturally. What I would recommend is that you store all of your times as standard UTC time. In SQL Server 2005 and older there is no way to store time zone information, but if everything is stored in universal time, you should be OK because the time can be converted to the local time later on.
SQL Server 2008 does have some datatypes that are aware of time zones, and if you're using .NET 3.5 there are tools to assist with time zone handling/conversions.
Definitely keep times in universal format. This will make a world of a difference if you have to work in multiple time zones.