python date strptime code example

Example 1: python datetime string

import datetime

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

Example 2: strptime python

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

Example 3: python example strptime

from datetime import datetime

date_string = "21 June, 2018"

print("date_string =", date_string)
print("type of date_string =", type(date_string))

date_object = datetime.strptime(date_string, "%d %B, %Y")

print("date_object =", date_object)
print("type of date_object =", type(date_object))

Example 4: python datetime to string iso format

from datetime import datetime
some_date = datetime.now()
iso_date_string = some_date.isoformat()

# For older version of python 
iso_date_string = some_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z')

Example 5: strptime python

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