Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Twitter's date format to Datetime in python

Tags:

python-2.7

date time format returned by Twitter is in this form:

Thu Apr 23 13:38:19 +0000 2009

I want it in datetime format for database enty and query...

like image 905
Sanky Cse Avatar asked Sep 10 '13 05:09

Sanky Cse


People also ask

How do I change date format in Python?

Python provides the strptime() method, in its datetime class, to convert a string representation of the​ date/time into a date object.

What is the date format on twitter?

When you choose a date and time (ex. Fri Nov 3 6:55 PM) the date on the post will have the day be the final two digits of the time (ex. 11/55/17).

How do I convert datetime to date in Python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.


2 Answers

EDIT - 13 Apr 15 As suggested, please use.

 datetime.strptime('Thu Apr 23 13:38:19 +0000 2009','%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC)

Now, if you want work much on the Date parsing and playing around with Date Time strings, use Babel or python-dateutil


Please ignore the suggestion below

I have not been working much on Python lately, but this should do the trick.

>>>from datetime import datetime
>>>d = datetime.strptime('Thu Apr 23 13:38:19 +0000 2009','%a %b %d %H:%M:%S %z %Y');
>>>print d.strftime('%Y-%m-%d');

This is based on Python Doc and SO

like image 118
aksappy Avatar answered Oct 18 '22 08:10

aksappy


Assuming your data is stored in a data frame "df" and the time for the tweet is stored in the "created_at" column. you can do:

df["created_at"] = df["created_at"].astype('datetime64[ns]') 
df["created_at"] = df.created_at.dt.to_pydatetime()
like image 35
Moniba Avatar answered Oct 18 '22 08:10

Moniba