strf datetime python code example

Example 1: strptime python

import datetime
d =datetime.datetime.strptime("01/27/2012","%m/%d/%Y").strftime('%m/%d/%Y')
print d
01/27/2012

Example 2: strftime python

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

Example 3: strptime python

import datetime
d = datetime.datetime.strptime("01/27/2012", "%m/%d/%Y")
print(d)
output ....
2012-01-27 00:00:00