Datetime strptime in python

后端 未结 5 546
小鲜肉
小鲜肉 2021-02-04 08:30

I\'ve tried the following code :

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

and the output is :

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 09:12

    There is a difference between datetime.strp[arse]time() and datetime.strf[ormat]time().

    The first one, strptime() allows you to create a date object from a string source, provided you can tell it what format to expect:

    strDate = "11-Apr-2019_09:15:42"
    dateObj = datetime.strptime(strDate, "%d-%b-%Y_%H:%M%S")
    
    print(dateObj)  # shows: 2019-04-11 09:15:42
    

    The second one, strftime() allows you to export your date object to a string in the format of your choosing:

    dateObj = datetime(2019, 4, 11, 9, 19, 25)
    strDate = dateObj.strftime("%m/%d/%y %H:%M:%S")
    
    print(strDate)  # shows: 04/11/19 09:19:25
    

    What you're seeing is simply the default string format of a datetime object because you didn't explicitly tell it what format to use.

    Checkout http://strftime.org/ for a list of all the different string format options that are availble.

提交回复
热议问题