Convert Odd Time Format To Hours
Hello, what's the easiest way to reformat a date that looks like '2017-01-01T19:33:28+0000' For example, that date means January 1st, 2017, at 7:33:28pm. I'm interested in removin
Solution 1:
You can use dateutil
:
import dateutil
t = dateutil.parse("2017-01-01T19:33:28+0000")
t.hour # prints 19
t.minute # prints 33
You can decide what you want to do with the hours and minutes later.
EDIT: By the way, this is in python.
Solution 2:
In R the lubridate
package has a lot of options for this (doc).
library(lubridate)
t <- as_datetime("2017-01-01T19:33:28+0000")
hour(t)
#[1]19minute(t)
#[1]33
You'll likely be particularly interested in the interval
function.
Solution 3:
This is a Python solution using datetime
, which belongs in the standard library:
from datetime import datetime
x = datetime.strptime('2017-01-01T19:33:28+0000', '%Y-%m-%dT%H:%M:%S%z')\
.strftime('%H:%M')
# '19:33'
Solution 4:
Not quite as feature rich as dateutil
but vectorized: numpy
>>> import numpy as np
>>> >>> example
['2018-01-01T12:00:00+0000', '2018-01-01T16:37:45+0000', '2018-01-01T21:15:30+0000', '2018-01-02T01:53:15+0000', '2018-01-02T06:31:00+0000', '2018-01-02T11:08:45+0000']
>>>
# create numpy array, 'M8' stands for datetime64>>> A = np.array(example, dtype='M8')
>>> A
array(['2018-01-01T12:00:00', '2018-01-01T16:37:45',
'2018-01-01T21:15:30', '2018-01-02T01:53:15',
'2018-01-02T06:31:00', '2018-01-02T11:08:45'],
dtype='datetime64[s]')
>>> # we have to manually extract hours and minutes but it is easy:# convert to units 'h' (hour, discarding minutes and seconds) and # 'D' (day, also discarding smaller units) and take the difference>>> hours = A.astype('M8[h]') - A.astype('M8[D]')
# and similar for minutes>>> minutes = A.astype('M8[m]') - A.astype('M8[h]')
>>> hours
array([12, 16, 21, 1, 6, 11], dtype='timedelta64[h]')
>>> minutes
array([ 0, 37, 15, 53, 31, 8], dtype='timedelta64[m]')
Solution 5:
The no-added-packages approach in R would be:
as.POSIXct( "2017-01-01T19:33:28+0000", format="%Y-%m-%dT%H:%M:%S%z", tz="UTC" )
[1] "2017-01-01 19:33:28 UTC"
Post a Comment for "Convert Odd Time Format To Hours"