Wednesday, July 16, 2014

How to convert date formats from YYYYMMDD to MM/DD/YYYY

YYYYMMDD2MM-DD-YYYY
In [1]:
from datetime import datetime
In [2]:
oldformat = '20140716'
datetimeobject = datetime.strptime(oldformat,'%Y%m%d')
In [3]:
newformat = datetimeobject.strftime('%m-%d-%Y')
print newformat
07-16-2014

In [4]:
newformat2 = datetimeobject.strftime('%m/%d/%Y')
print newformat2
07/16/2014

In [5]:
#Here is a link to the python strftime character references
#http://strftime.org/

7 comments:

  1. What if i datetime is like
    d='4/26/2018 10:45:19 PM'

    I tried this but didnt not worked

    datetimeobject = datetime.strptime(d,'%m/%d/%Y %H:%M:%S %p')
    newformat = datetimeobject.strftime('%Y-%m-%d %I:%M:%S')

    ReplyDelete
    Replies
    1. Though a very old post, sharing a link here for others to refer.

      The following link has formatting details related to date and time:
      https://stackabuse.com/how-to-format-dates-in-python/

      Delete
  2. Your code worked like a charm! Thank you

    ReplyDelete
  3. What if the date format is like "Monday, May 28, 2018 at 8:00 PM"

    ReplyDelete
  4. What if i want to print it like DAYMONTHYEAR, 21092020 ?

    ReplyDelete
  5. What if I have an API response that includes this date format: '/Date(1488281267907)/'
    How am I able to convert all these values to a normal date format throughout the whole file?

    ReplyDelete