Python Convert String To Datetime – Convert String To Datetime Using datetime Module

Welcome to my new Python Convert String To Datetime tutorial. In this post we will learn how to convert string into datetime object in python. But to understand this concept, firstly we will have to learn some basic information about datetime object in python, So let’s start.

Python Convert String To Datetime
Python Convert String To Datetime

Python Datetime Module – Exploring Datetime with Python

The concept of dealing with datetime is ridiculously simple in python. But it can be intimidating for beginners. So, that’s why i feel the need of explaining Date and Time in python firstly instead of going further.

datetime Module

  • datetime is a built-in module of python which helps you to deal with the date and time.
  •  It provide classes and methods for manipulating date and time in both simple and complex ways.
  • There are two kinds of date and time objects: “naive” and “aware”.

Getting Current Date and Time

So now we will see how to get current date and time in python. So let’s do that.

Importing datetime module

For importing datetime module you have to write the following code.

Getting Current Time And Date

If you want to know what time is it right now you have to simply do following things.

  • It will return a datetime object that contain all the information about the time which is right now.
  • You can see the output below.
Python Convert String To Datetime
Python Convert String To Datetime

Getting Date Individually

If you want to see only the current date then you have to do the following things.

  • First of all create a variable let’s say now_date.
  • With the help of now_date variable call the date() function.
  • That will give you date object. You must understand that date() itself is a big object which  contains some more data. So now date() will return a date object that contains year, month and day.
  • So you can see the output below.
Python Convert String To Datetime
Python Convert String To Datetime

Getting Time Individually

If you want to see only the current time then you have to write the following code.

It will return the time like this –

Python Convert String To Datetime
Python Convert String To Datetime

You can see the time format, it is displaying hour, minute, second and microsecond.

Also Read : Python Queue Example : Implementation, Examples and Types

Getting Any Value Individually

Now, if you want to get any value individually, let’s say only hour of the time or day of date. Then what will you do, you have to do some simple tricks, so let’s see them.

Getting current Hour

  • It will return the hour of current time.
Python Convert String To Datetime
Python Convert String To Datetime
Getting current Minute

  • It will return the minute of current time.
Python Convert String To Datetime
Python Convert String To Datetime
Getting current Second

  • It will return the Second of current time.
Python Convert String To Datetime
Python Convert String To Datetime

In this way, you can also get day, month, year of date individually.

Also Read :Recursive Function Python – Learn Python Recursion with Example

So now we will learn converting a given string  into datetime. So let’s start.

Python Convert String To Datetime Tutorial – Convert String Into Datetime

Let’s say, you have given a CSV file that contains some data in which one of the column is about time and the time is nothing but a string here like time=”10-9-2018 11:46:59″. This string contain date and time.This is in string format but if you want to do some pre computation on it using python then you need to convert this string into a datetime object. So that is what we will gonna learn like how to do that,right.

Importing datetime Module

Defining String

  • Now we have to define date and time in string format.

Calling Function strptime()

  • Now we have to call a function strptime()  that creates a datetime object from a string representing a date and time and a corresponding format string.
  • It takes two argument one is string representation of datetime and another one is pattern of the input string.
  • So the pattern here is like – you have the day, then a – , then the month, then a -, then the year, then a space, then hour, then : , then minute, then : , then second. So you have to follow that pattern.
  • And you have to put the pattern like “%d-%m-%Y %H:%M:%S” .
  • Here i have written %Y because i want to get long notation of the year and if you want to get short notation of year then just use %y. And %m is for month and %M is for minute.
  • So this is my pattern for the time here.

Printing Time In Datetime

  • Lastly just print the result.

Getting Code Together

  • So the whole code for converting string into datetime is as follows –

  • And the output of this code is as follows.
Python Convert String To Datetime
Python Convert String To Datetime

So our string is converted into datetime object successfully. And now if you want to get any individual option like day,minute, second etc then run the following code.

And you can see the output.

Python Convert String To Datetime
Python Convert String To Datetime

Examples Of Various Time Formats

Now, one question can arise in your mind that how to design pattern of the time. "%Y-%m-%d %H:%M:%S.%f" is known as format tokens with different meaning for each token. Check out the strptime format  for the list of all different types of format code that are supported in Python. So here i am showing you an example how to convert different string format into datetime.

And the output of this code is pretty cool.

Python Convert String To Datetime
Python Convert String To Datetime

Also Read : Python Lambda Function Tutorial – Working with Lambda Functions

Working With Timezone And Datetime

Now we will see how to display timezone and convert timezone. Before that we need to understand what is the UTC.

  • UTC is a time standard commonly used across the world.
  • The world’s timing centers have agreed to keep their time scale closely synchronized or co-ordinated, so the name is UTC(Universal Time Coordinated).

When we will deal with timezone then handling date-time becomes more difficult. In the previous examples, we have deal with only naive datetime object that means these type of objects does not contain any timezone related data.

Python provides a pytz library for  timezone conversion.

  • This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time.

Installing pytz module

Displaying Timezone

For getting timezone we have to run the following code.

So the output is as follows.

Python Convert String To Datetime
Python Convert String To Datetime

Converting date-time String Into Another Timezone

We can convert date-time strings to any other timezone. For example, we can convert the string “2018-10-09 12:08:00.586525+00:00” to “Africa/Asmara” timezone, as shown below:

What We Did ?

  • First of all we have converted a date-time string into datetime object i.e., date_time_object.
  • Then we converted datetime object into a timezone-enabled datetime object i.e., timezone_date_time_obj.
  • Here we have defined the timezone as ‘Africa/Asmara’. So you can clearly see the time in output is 3 hours behind than UTC time.
Python Convert String To Datetime
Python Convert String To Datetime

Converting Timezone

We can also convert timezone for different regions. So let’s see what we have to do for this.

What We Did ?

  • First of all i have fetched current time in UTC.
  • Then converted it into different time zones.
  • astimezone() method is used to convert time from one timezone to another timezone.
  • Here i am showing you a couple of timezone of different cities.

So the output of this code is as follows.

Python Convert String To Datetime
Python Convert String To Datetime

Now  you can clearly see that all regions have different timezone.

Also Read : Python Lambda Function Tutorial – Working with Lambda Functions

So friends this was all about Python Convert String To Datetime tutorial. I hope you will  have learned lots of knowledge from this post. And yes “Knowledge is Bless “ so keep sharing. In the upcoming post i will discuss about Python String To Datetime Libraries, so till then stay tuned with Simplified Python. And if you have any query regarding this post then just leave your comments. Thanks everyone.

Leave a Comment