datetime to string python | python datetime to string

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

Datetime strftime Method:-

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.

Converting from datetime to string:-

 Import datetime

                        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.

YY-MM-DD:-

            dt_stamp.strftime ('%y-%m-%d')

'19-01-09' 

%y means two-digit year.

MM-DD-YYYY:-

            dt_stamp.strftime ('%m-%d-%Y') 
            '01-09-2019' 

MM-DD-YY:-

            dt_stamp.strftime ('%m-%d-%y') 
            '01-09-19' 

DD-MM-YYYY:-

             dt_stamp.strftime ('%d-%m-%Y') 
             '09-01-2019' 

DD-MM-YY:-

              dt_stamp.strftime ('%d-%m-%y') 
              '09-01-19' 

YYYY/MM/DD

               dt_stamp.strftime ('%Y/%m/%d') 
               '2019/01/09' 

YY/MM/DD:-

               dt_stamp.strftime ('%y/%m/%d') 
               '19/01/09' 

MM/DD/YYYY:-

               dt_stamp.strftime ('%m/%d/%Y') 
               '01/09/2019' 

MM/DD/YY:-

               dt_stamp.strftime ('%m/%d/%y') 
              '01/09/19' 
               dt_stamp.strftime ('%D') 
               '01/09/19' 

             %D is the shortcut for %m/%d/%y.

DD/MM/YYYY:-

              dt_stamp.strftime ('%d/%m/%Y') 
              '09/01/2019' 

DD/MM/YY:-

             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)
Additional Services : Refurbished Laptops Sales, Python Classes, Share Market Classes And SEO Freelancer in Pune, India