datetime to string python | python datetime to string: datetime.strftime ():-
The python’s datetime class will provide a member function strftime () to create a string of data in the object.
Datetime.strtime (Format_string)
Also, accept the argument and cover data in object to a string.
To import datetime class we use,
From datetime import datetime
The method is used to convert datetime to string and use strftime method of datetime object.
Datetime_object.strftime (“%m/%d%Y, %H: %M: %S”)
If it includes time zones then datetime object should be timezone aware.
dt_stamp = datetime.datetime (2019, 1, 9)
type (dt_stamp)
datetime.datetime
str (dt_stamp)
'2019-01-09 00:00:00'
Then convert datetime objects and panda and Timestamp object to string with str.
dt_stamp.strftime ('%Y-%m-%d')
'2019-01-09'
dt_stamp.strftime ('%F')
'2019-01-09'
The %Y means four-digit year, %m represent two-digit month, %d will describe two-digit day, %F is the shortcut for %Y-%m-%d.
dt_stamp.strftime ('%y-%m-%d')
'19-01-09'
%y means two-digit year.
dt_stamp.strftime ('%m-%d-%Y')
'01-09-2019'
dt_stamp.strftime ('%m-%d-%y')
'01-09-19'
dt_stamp.strftime ('%d-%m-%Y')
'09-01-2019'
dt_stamp.strftime ('%d-%m-%y')
'09-01-19'
dt_stamp.strftime ('%Y/%m/%d')
'2019/01/09'
dt_stamp.strftime ('%y/%m/%d')
'19/01/09'
dt_stamp.strftime ('%m/%d/%Y')
'01/09/2019'
dt_stamp.strftime ('%m/%d/%y')
'01/09/19'
dt_stamp.strftime ('%D')
'01/09/19'
%D is the shortcut for %m/%d/%y.
dt_stamp.strftime ('%d/%m/%Y')
'09/01/2019'
dt_stamp.strftime ('%d/%m/%y')
'09/01/19'
Here convert timestamp in a datetime object,
DatetimeObj=datetime.now ()
Here datetime object is converted into the string format as’DD-MMM-YYYY’,
Timestampstr=datetimrObj.strftime (“%d-%b-%Y (%H: %M: %S. %f)”)
Print(‘Current Timestamp:’, timestampStr)
Output:-
Current Timestamp: 18-nov-2918(08:34:58.674035)