/  Technology   /  Converting string into datetime

Converting string into datetime

Converting string into datetime

We can convert a string representation of date and time into a date object using the two methods mentioned below

    • Using datetime module

 

 

  • Using dateutil module

 

Using the datetime module:

 

We import a datetime class named datetime from the datetime module. We use this class to call the strptime() method. The strptime() method creates a datetime object from the given string. 

 

Note: We cannot create a datetime object from every string. The string needs to be in a certain format.

 

This method takes two arguments 

  • string which represents date and time
  • format code 

 

The most frequently used format codes are 

  • %d which represents the day of the month. 

Example: 01, 02, …, 31

 

  • %B which represents the complete month’s name .

Example: January, February etc.

 

  • %Y which represents the year that is four digits long. 

Example: 2018, 2019 etc.

 

  • %I which represents 12 hour clock as a zero padded decimal 

Example:01, 02, …, 12

 

  • %p which represents whether it’s AM or PM.

 

  • %M which represents minutes as a zero-padded decimal.

Example:01, 02, …, 59

Using the dateutil module:

From the dateutil module we import the parser class using which we call the parser() class method. We only pass one parameter which is the string. 

Leave a comment