strptime()

strptime() : Returns date object from input string with format details.

Date input

from datetime import datetime
str_date='2021-8-25' # date as string 
dt=datetime.strptime(str_date,'%Y-%m-%d')
print(type(dt)) # 
print(dt) #2021-08-25 00:00:00

Example

from datetime import datetime
str_date='28021985' # date as string 
dt=datetime.strptime(str_date,'%d%m%Y')
print(dt.year,dt.month,dt.day)  # 1985 2 28
# adding format 
print(dt.strftime('%Y-%m-%d'))  # 1985-02-28

Date with time

from datetime import datetime
str_date='2021/8/25 13:45:53' # date as string 
dt=datetime.strptime(str_date,'%Y/%m/%d %H:%M:%S')
print(dt) # 2021-08-25 13:45:53

Using Microsecond

str_date='2021/8/25 13:45:53 341789' # date as string 
dt=datetime.strptime(str_date,'%Y/%m/%d %H:%M:%S %f')
print(dt) # 2021-08-25 13:45:53.341789

Wrong format

In case format is not matching , then we will get ValueError.
str_date='2021-8-25' # date as string 
dt=datetime.strptime(str_date,'%Y/%m/%d')
ValueError: time data '2021-8-25' does not match format '%Y/%m/%d'
List of format codes used with strptime() is here
All Date Objects

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer