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 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.
1 2 3 |
from datetime import datetime |
Getting Current Time And Date
If you want to know what time is it right now you have to simply do following things.
1 2 3 |
print(datetime.now()) |
- It will return a datetime object that contain all the information about the time which is right now.
- You can see the output below.
Getting Date Individually
If you want to see only the current date then you have to do the following things.
1 2 3 4 5 6 7 |
from datetime import datetime now_date = datetime.now() print(now_date.date()) |
- 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.
Getting Time Individually
If you want to see only the current time then you have to write the following code.
1 2 3 4 5 6 7 |
from datetime import datetime current_time = datetime.now() print("Current Time is :", current_time.time()) |
It will return the time like this –
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
1 2 3 4 5 6 7 |
from datetime import datetime current_time = datetime.now() print("Current Hour is :", current_time.hour) |
- It will return the hour of current time.
Getting current Minute
1 2 3 4 5 6 7 |
from datetime import datetime current_time = datetime.now() print("Current Minute is :", current_time.minute) |
- It will return the minute of current time.
Getting current Second
1 2 3 4 5 6 7 |
from datetime import datetime current_time = datetime.now() print("Current Second is :", current_time.second) |
- It will return the Second of current time.
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
1 2 3 |
from datetime import datetime |
Defining String
- Now we have to define date and time in string format.
1 2 3 |
time_in_string = "8-10-2018 11:52:40" |
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.
1 2 3 |
time_in_datetime = datetime.strptime(time_in_string, "%d-%m-%Y %H:%M:%S") |
Printing Time In Datetime
- Lastly just print the result.
1 2 3 |
print(" Time in Datetime Format :", time_in_datetime) |
Getting Code Together
- So the whole code for converting string into datetime is as follows –
1 2 3 4 5 6 7 8 9 |
from datetime import datetime time_in_string = "8-10-2018 11:52:40" time_in_datetime = datetime.strptime(time_in_string, "%d-%m-%Y %H:%M:%S") print(" Time in Datetime Format :", time_in_datetime) |
- And the output of this code is as follows.
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.
1 2 3 |
print(" Day in Datetime Format :", time_in_datetime.day) |
And you can see the output.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from datetime import datetime date_time_str1 = 'Jun 28 2018 7:40AM' date_time_str2 = 'September 18, 2017, 22:19:55' date_time_str3 = 'Sun,05/12/99,12:30PM' date_time_str4 = '2018-03-12T10:12:45Z' date_time_obj1 = datetime.strptime(date_time_str1, '%b %d %Y %I:%M%p') date_time_obj2 = datetime.strptime(date_time_str2, '%B %d, %Y, %H:%M:%S') date_time_obj3 = datetime.strptime(date_time_str3, '%a,%d/%m/%y,%I:%M%p') date_time_obj4 = datetime.strptime(date_time_str4, '%Y-%m-%dT%H:%M:%SZ') print('For Time1 Date:',date_time_obj1.date(), 'Time:', date_time_obj1.time()) print('For Time2 Date:',date_time_obj2.date(), 'Time:', date_time_obj2.time() ) print('For Time3 Date:',date_time_obj3.date(), 'Time:', date_time_obj3.time() ) print('For Time4 Date:',date_time_obj4.date(), 'Time:', date_time_obj4.time() ) |
And the output of this code is pretty cool.
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
1 2 3 |
easy_install --upgrade pytz |
Displaying Timezone
For getting timezone we have to run the following code.
1 2 3 4 5 6 7 8 9 10 |
from datetime import datetime from pytz import timezone Time_format = "%Y-%m-%d %H:%M:%S %Z%z" #get the current time in UTC now_utc_time = datetime.now(timezone('UTC')) print('UTC :', now_utc_time) |
So the output is as follows.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from datetime import datetime import pytz date_time_string = '2018-10-09 12:08:00' date_time_object = datetime.strptime(date_time_string, '%Y-%m-%d %H:%M:%S') timezone = pytz.timezone('Africa/Asmara') timezone_date_time_obj = timezone.localize(date_time_object) print(timezone_date_time_obj) print(timezone_date_time_obj.tzinfo) |
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.
Converting Timezone
We can also convert timezone for different regions. So let’s see what we have to do for this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from datetime import datetime from pytz import timezone Time_format = "%Y-%m-%d %H:%M:%S %Z%z" #get the current time in UTC now_utc_time = datetime.now(timezone('UTC')) print('UTC :', now_utc_time) #convert this to EST now_est_time = now_utc_time.astimezone(timezone('US/Eastern')) print('EST :', now_est_time) now_berlin_time = now_utc_time.astimezone(timezone('Europe/Berlin')) print('Berlin :', now_berlin_time) now_kolkata_time = now_utc_time.astimezone(timezone('Asia/Kolkata')) print('Kolkata :', now_kolkata_time) now_shanghi_time = now_utc_time.astimezone(timezone('Asia/Shanghai')) print('Shanghai :', now_shanghi_time) |
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.
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.