Home » Python » Convert datetime object to a String of date only in Python

Convert datetime object to a String of date only in Python

Posted by: admin November 1, 2017 Leave a comment

Questions:

I see a lot on converting a datetime string to an datetime object in Python, but I want to go the other way.
I’ve got datetime.datetime(2012, 2, 23, 0, 0) and I would like to convert it to string like '2/23/2012'.

Answers:

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here

Questions:
Answers:

date and datetime objects (and time as well) support a mini-language to specify output, and there are two ways to access it:

  • direct method call: dt.strftime('format here'); and
  • new format method: '{:format here}'.format(dt)

So your example could look like:

dt.strftime('%m/%d/%Y')

or

'{:%m/%d/%Y}'.format(dt)

For completeness’ sake: you can also directly access the attributes of the object, but then you only get the numbers:

'%s/%s/%s' % (dt.month, dt.day, dt.year)

The time taken to learn the mini-language is worth it.


For reference, here are the codes used in the mini-language:

  • %a Weekday as locale’s abbreviated name.
  • %A Weekday as locale’s full name.
  • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
  • %d Day of the month as a zero-padded decimal number.
  • %b Month as locale’s abbreviated name.
  • %B Month as locale’s full name.
  • %m Month as a zero-padded decimal number. 01, …, 12
  • %y Year without century as a zero-padded decimal number. 00, …, 99
  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %H Hour (24-hour clock) as a zero-padded decimal number. 00, …, 23
  • %I Hour (12-hour clock) as a zero-padded decimal number. 01, …, 12
  • %p Locale’s equivalent of either AM or PM.
  • %M Minute as a zero-padded decimal number. 00, …, 59
  • %S Second as a zero-padded decimal number. 00, …, 59
  • %f Microsecond as a decimal number, zero-padded on the left. 000000, …, 999999
  • %z UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030
  • %Z Time zone name (empty if naive), UTC, EST, CST
  • %j Day of the year as a zero-padded decimal number. 001, …, 366
  • %U Week number of the year (Sunday is the first) as a zero padded decimal number.
  • %W Week number of the year (Monday is first) as a decimal number.
  • %c Locale’s appropriate date and time representation.
  • %x Locale’s appropriate date representation.
  • %X Locale’s appropriate time representation.
  • %% A literal ‘%’ character.
Questions:
Answers:

Another option:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

Questions:
Answers:

You could use simple string formatting methods:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

Questions:
Answers:

type-specific formatting can be used as well:

t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)

Output:

'02/23/2012'

Questions:
Answers:

String concatenation, str.join, can be used to build the string.

 d = datetime.now()
 '/'.join(str(x) for x in (d.month, d.day, d.year))
 '3/7/2016'

Questions:
Answers:

You can convert datetime to string.

published_at="{}".format(self.published_at)

Questions:
Answers:

It is possible to convert a datetime object into a string by working directly with the components of the datetime object.

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

Output –> 5/23/2017