Date Time Conversion and Extract Only Time

Date time conversion and extract only time

If your data is

a <- "17:24:00"

b <- strptime(a, format = "%H:%M:%S")

you can use lubridate in order to have a result of class integer

library(lubridate)
hour(b)
minute(b)

# > hour(b)
# [1] 17
# > minute(b)
# [1] 24

# > class(minute(b))
# [1] "integer"

and you can combine them using

# character
paste(hour(b),minute(b), sep=":")

# numeric
hour(b) + minute(b)/60

for instance.

I would not advise to do that if you want to do any further operations on your data. However, it might be convenient to do that if you want to plot the results.

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

Converting datetime only to time in pandas

How about that?

>>> df['TimeOnly']=df['Date Created'].dt.strftime('%H:%M:%S')

>>> df
Date Created TimeOnly
0 2016-02-20 09:26:45 09:26:45
1 2016-02-19 19:30:25 19:30:25
2 2016-02-19 18:13:39 18:13:39
3 2016-03-01 14:15:36 14:15:36
4 2016-03-04 14:47:57 14:47:57

Extracting just Month and Year separately from Pandas Datetime column

If you want new columns showing year and month separately you can do this:

df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month

or...

df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month

Then you can combine them or work with them just as they are.

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

How do I convert a datetime to date?

Use the date() method:

datetime.datetime.now().date()


Related Topics



Leave a reply



Submit