How to convert a String to DateTime in Python

In this python tutorial, we will discuss Python Converting a string to DateTime. We will also check:

  • Python convert a string to datetime object
  • How to convert a string to datetime with timezone in Python
  • Python convert a string to datetime without format
  • Python converting a string to datetime pandas
  • Python converting a string to datetime iso format
  • Python converting a string to datetime with milliseconds
  • Python converting a string to datetime yyyy-mm-dd
  • Python converting a string to timestamp
  • Python converting a string to datetime.date
  • Python converting a datetime to string
  • How to convert a string to datetime UTC in Python

Convert a String to DateTime in Python

Let us see, how to convert a string into datetime in python.

In this example, I have imported a module called datetime.

Example:

import datetime
print((datetime.datetime.now()))

To get the output we will print((datetime.datetime.now())). You can refer to the below screenshot for the output:

Python Converting a string to DateTime
Python Converting a string to DateTime

How to convert a string to datetime object in Python

Let us see, how to convert a string into datetime object in python.

  • In this example, I have imported a module called datetime, passed a variable as dt_string = “2020-12-18 3:11:09“, and assigned format = “%Y-%m-%d %H:%M:%S” .
  • I have used strptime string. This string represents a time according to format.
  • dt_object = datetime.datetime.strptime(dt_string, format) used to create datetime object.

Example:

import datetime
dt_string = "2020-12-18 3:11:09" 
format = "%Y-%m-%d %H:%M:%S"
dt_object = datetime.datetime.strptime(dt_string, format)
print("Datetime: ", dt_object)
print("Minute: ", dt_object.minute)
print("Hour: ", dt_object.hour)
print("Second: ", dt_object.second)

To get the output as datetime object print(“Datetime: “, dt_object), to get minute object print(“Minute: “, dt_object.minute), to get hour object print(“Hour: “, dt_object.hour) and, to get second object print(“Second: “, dt_object.second).

You can refer below screenshot for the output:

Python converting a string to datetime object
Python converting a string to datetime object

Convert a string to datetime pandas in Python

Now, we can see how to convert a string to datetime pandas in python.

In this example, I have a module called pandas. Pandas is a library that is used for data science. Here, we will import pandas as pd. The pd.to_datetime(dt) method is used to convert the string datetime into a datetime object using pandas in python.

Example:

import pandas as pd
dt = ['21-12-2020 8:40:00 Am']
print(pd.to_datetime(dt))
print(dt)

To get the output as datetime object print(pd.to_datetime(dt)) is used.

You can refer the below screenshot for the output:

Python converting a string to datetime pandas
Python converting a string to datetime pandas

Python convert a string to datetime with timezone

Now, we can see how to convert a string to datetime with timezone in python.

In this example, I have imported a module called timezone. datetime.now(timezone(‘UTC’)) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”. The %z is used to get timezone along with datetime.

Example:

from datetime import datetime
from pytz import timezone
time = "%Y-%m-%d %H:%M:%S %Z%z"
time = datetime.now(timezone('UTC'))
print('UTC :', time)

To get the output print(‘UTC :’, time) is used. In the below screenshot, we can see the output.

Python converting a string to datetime with timezone
Python converting a string to datetime with timezone

Python convert a string to datetime with milliseconds

Let us see how to convert a string to datetime with milliseconds in python.

In this example, I have imported a module called datetime. The dt = datetime.datetime.now() is used to get the present time. Here, %f is used to get time with milliseconds.

Example:

import datetime
dt = datetime.datetime.now()
dt.strftime('%Y/%m/%d %H:%M:%S.%f')
print(dt)

To get the output as datetime with milliseconds print(dt). You can refer to the below screenshot for the output:

datetime with millisecond 2
Python converting a string to datetime with milliseconds

Python converting a string to datetime without format

Now we can see, how to convert string to datetime without format in python.

In this example, I have imported a module called a parser. The parser function will parse a string automatically in the dt variable. dateutil module is the extension for the standard datetime module. The datetime string is passed without format.

Example:

from dateutil import parser
dt = parser.parse("Dec 21 2020  1:01PM")
print(dt)

To get the final result print(dt) is used. Below screenshot shows the output:

Python converting a string to datetime without format
Python converting a string to datetime without format

Python converting a string to datetime iso format

Here, we can see how to converting a string to datetime iso format in python

In this example, I have imported a module called datetime and used .isoformat to convert present time into iso format.

Example:

from datetime import datetime
dt = datetime.now()
print(dt.isoformat())

To get the output in iso format, here I have used print(dt.isoformat()). You can see the below screenshot for output:

Python converting a string to datetime iso format
Python converting a string to datetime iso format

Python convert a string to datetime yyyy-mm-dd

Now we can see, how to convert a string to datetime yyyy-mm-dd in python.

  • In this example, I have imported a module called datetime. And assigned input as “2020-12-21” to the variable as dt_string, and the format as format = “%Y-%m-%d”.
  • strptime is a string that represents a time according to format.
  • dt_object = datetime.datetime.strptime(dt_string, format) In this two arguments are passed one is dt_string and other one is format.

Example:

import datetime
dt_string = "2020-12-21" 
format = "%Y-%m-%d" 
dt_object = datetime.datetime.strptime(dt_string, format)
print(dt_object)

To get the output print(dt_object) is used in this example. You can refer to the below screenshot for the output:

datetime with yyyymmdd
Python converting a string to datetime yyyy-mm-dd

How to convert a string to timestamp in Python

Here, we can see how to convert a string into timestamp in Python.

In this example, I have imported a module called datetime and assigned an input string as a date and the strptime string is used to get the time in the format. Timestamp() is a function that returns the time in the form of seconds.

Example:

import datetime 
date = "21/12/2020"
time = datetime.datetime.strptime(date,"%d/%m/%Y") 
ts = datetime.datetime.timestamp(time) 
print(ts) 

To get the output print(ts) is used. In the below screenshot, you can see the output in which the time is in the form of seconds.

Python converting a string to timestamp
Python converting a string to timestamp

Python converting a string to datetime.date

  • Here, we can see how to convert a string to datetime.date in python.
  • In this example, I have imported a module called datetime and passed an input string as ‘2020/12/21’
  • To get only get date format as the output, we have to manually divide and pass the split string for the input string. And convert it by using int datatype, and also assign the index values for the input string.

Example:

import datetime
month = '2020/12/21'
date = datetime.date(int(month.split('/')[0]),int(month.split('/')[1]),int( month.split('/')[2]))
print(date)

To get the output print(date) is used. You can refer the below screenshot for the output.

Python converting a string to datetime.date
Python converting a string to datetime.date

Python converting a datetime to string

Here, we can see how to convert a datetime to string in python.

In this example, I have imported a module called datetime. The datetime.now() is used to get the present datetime. Here, strftime is a string used to get the time proper format, and “%d” is used to get only a date string.

Example:


from datetime import datetime
result = datetime.now()
date = result.strftime("%d")
print(date)

To get the output as date, I have used print(date). Below screenshot shows the output:

Python converting a datetime to string
Python converting a datetime to string

How to convert a string to datetime UTC in Python

Here, we can see how to convert a string to datetime utc format in Python.

  • In this example, I have imported modules called pytz and datetime. And assigned timezone as pytz.timezone (“Asia/Kolkata“).
  • Pytz is a library used for timezone calculation and lc.localize() is used to make a naive timezone. A simple datetime object is called a timezone naive, and lc_datetime.astimezone() is a function used to set the time according to the required timezone.

Example:

import pytz, datetime
lc = pytz.timezone ("Asia/kolkata")
datetime = datetime.datetime.strptime ("2020-12-22 10:11:12", "%Y-%m-%d %H:%M:%S")
lc_datetime = lc.localize(datetime)
utc_date_time = lc_datetime.astimezone(pytz.utc)
print(utc_date_time)

To get the output as time in UTC format print(utc_date_time), and it will return date and time. You can refer to the below screenshot for the output.

Python converting a string to datetime utc
Python converting a string to datetime utc

You may like the following Python tutorials:

In this Python tutorial, we have learned about how to convert a string to DateTime in Python. Also, We covered these below topics:

  • Python convert a string to datetime object
  • Python convert a string to datetime with timezone
  • Python convert a string to datetime without format
  • Python convert a string to datetime pandas
  • Python convert a string to datetime iso format
  • Python convert a string to datetime with milliseconds
  • Python convert a string to datetime yyyy-mm-dd
  • Python convert a string to timestamp
  • How to convert a string to datetime.date in Python
  • Python convert a datetime to string
  • Python convert a string to datetime UTC