Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to convert datetime format? [duplicate]

Tags:

python

date

Possible Duplicate:
How to convert a time to a string

I have a variable as shown in the below code.

a = "2011-06-09" 

Using python, how to convert it to the following format?

"Jun 09,2011" 
like image 440
Rajeev Avatar asked Jun 09 '11 06:06

Rajeev


People also ask

How do I convert datetime to different formats in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

How do I change the date format in a Dataframe in Python?

Function usedstrftime() can change the date format in python.


2 Answers

>>> import datetime >>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d') >>> d.strftime('%b %d,%Y') 'Jun 09,2011' 

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

like image 181
NPE Avatar answered Oct 13 '22 00:10

NPE


@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y')) 
like image 21
mgiuca Avatar answered Oct 13 '22 00:10

mgiuca