6: Date Formatting in Python

Section 6.1: Time between two date-times

from datetime import datetime

datetime(2016,10,06,0,0,0)

datetime(2016,10,01,23,59,59)

a-b

# datetime.timedelta(4, 1)

(a-b).days

# 4 (a-b).total_seconds()

# 518399.0

Section 6.2: Outputting datetime object to string

Uses C standard format codes.

from datetime import datetime

datetime_for_string datetime(2016,10,1,0,0) datetime_string_format ‘%b %d %Y, %H:%M:%S’ datetime.strftime(datetime_for_string,datetime_string_format)

# Oct 01 2016, 00:00:00

Section 6.3: Parsing string to datetime object

Uses C standard format codes.

from datetime import datetime

datetime_string ‘Oct 1 2016, 00:00:00’ datetime_string_format ‘%b %d %Y, %H:%M:%S’ datetime.strptime(datetime_stringdatetime_string_format)

# datetime.datetime(2016, 10, 1, 0, 0)

 

 

 

 

 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow. 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow.  This work is licensed under cc by-sa.