2

I scraped data from Twitter and I got my date format as 2020-01-07T22:24:20.000Z. I need to convert it to datetime format.

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
dee dee
  • 21
  • 2

3 Answers3

3

We can convert a string to pandas datetime(Timestamp) type using pd.to_datetime method.

pd.to_datetime('2020-01-07T22:24:20.000Z')

Output

Timestamp('2020-01-07 22:24:20+0000', tz='UTC')

If you have a column which needs to be converted to datetime, then

Input

df = DataFrame({
    'time':['2020-01-07T22:24:20.000Z', '2020-01-08T22:24:20.000Z']
})

    time
0   2020-01-07T22:24:20.000Z
1   2020-01-08T22:24:20.000Z

Conversion

df['time'] = pd.to_datetime(df.time)
df

Output

    time
0   2020-01-07 22:24:20+00:00
1   2020-01-08 22:24:20+00:00
Utsav
  • 5,050
  • 2
  • 22
  • 34
0

You could use the datetime library

import datetime as dt

date = '2020-01-07T22:24:20.000Z'


formatted = dt.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.000Z')

Output is Out[25]: datetime.datetime(2020, 1, 7, 22, 24, 20) Note that the decimals from the seconds and the characters T and Z where inserted in my strptime() call

  • using a literal `Z` in the parsing directive leads to naive datetime (tzinfo not set to UTC) - which is wrong in my opinion since Z denotes UTC and Python treats naive datetime as *local time*, not UTC. – FObersteiner May 07 '21 at 19:54
-1

You need to parse the date first

function parseTwitterDate(aDate)
{   
  return new Date(Date.parse(aDate.replace(/( \+)/, ' UTC$1')));
  //sample: Wed Mar 13 09:06:07 +0000 2013 
}

Then you can convert it to time

console.log(parseTwitterDate('2020-01-07T22:24:20.000Z').getTime());

This should return the timestamp, This code for javascript and hope it will help you

Hussam Kurd
  • 5,517
  • 1
  • 35
  • 35