How to cast the DateTime to Time
Time
is not stored with its display format in SQL Server.
Therefore, from the user perspective, you can say that it has no format.
Of course, that's not completely accurate since it does have a storage format, but as an average user you can't really use it.
This is true for all date and time data types:Date
, DateTimeOffset
, DateTime2
, SmallDateTime
, DateTime
and Time
.
If you need a format then you don't need to cast to time
but to a char
. Use Convert
to get the char
you need:
SELECT CONVERT(char(10), [time], 108) as CSTTime
Here is some background data if you're interested:
In this article published in 2000 the writer explains in depth how SQL Server treats dates and times. I doubt if anything significant changed between 2000 and 2015 in the way SQL Server stores date
, time
and datetime
values internally.
Here are the relevant quotes, if you don't want to read all of it:
So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers.
........
........
SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms).
since time
is actually stored as a 4 byte integer, it really doesn't have a format as an integral part of the data type.
You might also want to check out this article for a more detailed explanation with code samples.
How to get Time from DateTime format in SQL?
SQL Server 2008:
SELECT cast(AttDate as time) [time]
FROM yourtable
Earlier versions:
SELECT convert(char(5), AttDate, 108) [time]
FROM yourtable
Convert datetime to time in python
You can use the strftime
method of the datetime
object like this:
day.strftime('%H:%M')
More information here: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Ok, I misunderstood. Use day.time()
to get a time
object.
convert datetime to time
You can format the object as
strdate = convert.todatetime(object);
strdate .tostring("hh:mm tt");
or
strdate.toshorttime();
How to convert datetime to date only (with time set to 00:00:00.000)
For SQL Server 2005 and below:
CONVERT(varchar(8), @ParamDate, 112) -- Supported way
CAST(FLOOR(CAST(@ParamDate AS float)) AS DATETIME) -- Unsupported way
For SQL Server 2008 and above:
CAST(@ParamDate AS DATE)
How to convert datetime to integer in python
It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime
module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp())
.
If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:
2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)
def to_integer(dt_time):
return 10000*dt_time.year + 100*dt_time.month + dt_time.day
E.g.
In [1]: import datetime
In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
: return 10000*dt_time.year + 100*dt_time.month + dt_time.day
: # Or take the appropriate chars from a string date representation.
:--
In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613
If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.
I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.
It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.
Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.
It's generally much better to leave the value in a date context, like datetime.date
, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.
pandas convert from datetime to integer timestamp
You can typecast to int using astype(int)
and divide it by 10**9
to get the number of seconds to the unix epoch start.
import pandas as pd
df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]})
df_unix_sec = pd.to_datetime(df['time']).astype(int)/ 10**9
print(df_unix_sec)
How to convert DateTime to VarChar
With Microsoft Sql Server:
--
-- Create test case
--
DECLARE @myDateTime DATETIME
SET @myDateTime = '2008-05-03'
--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
how to cast a datetime to a specific 24 hour time
Use date_format:
SELECT count(*), date_format(dated, "%Y:%m:%d %H") AS hour
FROM posts
GROUP BY hour
Or to get just the hour, regardless of day:
SELECT count(*), HOUR(dated) AS hour
FROM posts
GROUP BY hour
How to return only the Date from a SQL Server DateTime datatype
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))
for example
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
gives me
2008-09-22 00:00:00.000
Pros:
- No varchar<->datetime conversions required
- No need to think about locale
Related Topics
Split Function Equivalent in T-Sql
Best Way to Do Multi-Row Insert in Oracle
Optimal Way to Concatenate/Aggregate Strings
SQL Statement Is Ignoring Where Parameter
Join Between Tables in Two Different Databases
Maximum Size For a SQL Server Query? in Clause? Is There a Better Approach
Passing Multiple Values For a Single Parameter in Reporting Services
Truncate (Not Round) Decimal Places in SQL Server
Insert Text With Single Quotes in Postgresql
How to Check If a Table Exists in a Given Schema
What Is the Major Difference Between Varchar2 and Char
Postgresql Distinct on With Different Order By
Cannot Insert Explicit Value For Identity Column in Table 'Table' When Identity_Insert Is Set to Off