Rapidistul
Rapidistul

Reputation: 564

Convert tweet creation time to UTC

Building a Twitter scraper I'm stuck at converting tweet creation datetime (I get it as local timezone) into UTC.

Creation date from data-original-title -attribute's format is 12:17 AM - 8 Apr 2018. How can I convert it to UTC?

Upvotes: 1

Views: 419

Answers (2)

Rohit Khanna
Rohit Khanna

Reputation: 57

Try Below:

import pandas as pd
datestr = '12:17 AM - 8 Apr 2018'
utcDate = pd.to_datetime(datestr, format='%H:%M %p  - %d %b %Y', utc=True)

Upvotes: 1

Chiheb Nexus
Chiheb Nexus

Reputation: 9267

First of all you need to convert your string into a python datetime format then i recommend you using pytz module to change the timezone used into UTC timezone like this example:

import datetime
import pytz
a = '12:17 AM - 8 Apr 2018'
final = datetime.datetime.strptime(a, '%I:%M %p - %d %b %Y').replace(tzinfo=pytz.UTC)
print(final)
# 2018-04-08 00:17:00+00:00

Also, if you want to check the converted time into a string representation, you can do :

str_time = final.strftime('%d/%m/%Y %H:%M:%S')
print(str_time)
# '08/04/2018 00:17:00'

Ps: If you don't have pytz module installed in your PC, you can install it by :

sudo pip install pytz

Upvotes: 1

Related Questions