Python datetime strptime | Convert string to datetime Example

With Python Datetime strptime function, you can convert a string to DateTime. The strptime function is available in DateTime and time modules, you have to import one of them to parse a string to DateTime and time objects respectively.

“strptime = String parse time”

Python datetime strptime | Convert string to datetime Example

Syntax

Python strptime() is a class method in datetime class.

OR

Time module has the similar function available, here is syntax

Python datetime strptime Example

For a get datetime class, you need to import DateTime module.

Output: 2018-10-11 14:35:32

OR – the Same example for above, import “from module_name.member_name” datetime.

Get the Time from String 

Example of get the TIME only.

Output: 15:35:36

Get the Date from String 

Example of get the DATE only.

Output: 2018-10-11

Python time strptime example

You have to import a time module for this example.

Output: time.struct_time(tm_year=2018, tm_mon=10, tm_mday=11, tm_hour=14, tm_min=35, tm_sec=32, tm_wday=3, tm_yday=284, tm_isdst=-1)

Python strptime() format directives

Here is a list of formate directives used in strptime() function.

DirectiveDescriptionExample
%aShort name of weekdayFri
%AFull name of WeekdayFriday
%wWeekday as a number 0-6, 0 is Sunday – 0 Monday – 1 …5
%dDay of month 01-3101
%bMonth name, short versionOct
%BMonth name, full versionOctober
%mMonth as a number 01-1210
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2300
%IHour 00-1212
%pAM/PMAM
%MMinute 00-5938
%SSecond 00-5901
%fMicrosecond 000000-999999844628
%zUTC offset+0100
%ZTimezoneUTC+01:00
%jDay number of year 001-366283
%UWeek number of year, Sunday as the first day of the week, 00-5340
%WWeek number of year, Monday as the first day of the week, 00-5341
%cLocal version of date and timeWed Oct 10 03:38:01 2018
%xLocal version of date10/10/18
%XLocal version of time03:38:01
%%A % character%

Error: module ‘datetime’ has no attribute ‘strptime’?

Use 2-time DateTime because datetime is also stood for the module. So you need to access datetime class then strptime function.

or use  import “from module_name.member_name” datetime.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.