convert time to datetime python code example

Example 1: convert into date python

date_str = '09-19-2018'

date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object)  # printed in default formatting

Example 2: timestamp to date python

from datetime import datetime

timestamp = 1586507536367
dt_object = datetime.fromtimestamp(timestamp)

Example 3: convert timestamp to date using python

from datetime import datetime

timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

Example 4: converting datetime object format to datetime format python

df['date_time']=pd.to_datetime(df['date_time'], format='%d-%m-%Y %H.%M.%S')
#fomrat given in code should match the format of the feature
#here--> df['date_time'][0]=10-03-2004 18.00.00
#watchout for the blanks  '-' '.'

Example 5: convert datetime to date python

datetime.datetime.now().date()

Example 6: python string to datetime python

from dateutil import parser
datetime_object = parser.parse("Jun 1 2020  1:36PM")