Datetime python convert string to date

How to Convert a String to DateTime in Python?

This Python tutorial explains, how to convert a string to datetime in Python. I will also show you, how to convert string to datetime with timezone in Python.

Converting a string to a DateTime object is a common task when you’re dealing with data that involves timestamps. Python makes this relatively straightforward with the help of the datetime module.

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.

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 datetime format with timezone

Convert a string to datetime with timezone in Python

In Python, converting a string into a datetime object with a timezone requires using the datetime module. Specifically, you’ll have to work with the datetime class, the timezone class, and the strptime method.

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 the 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.

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 string to datetime with timezone

Convert string to datetime with timezone in Python

Converting a string to a datetime object with a timezone in Python involves parsing the string into a datetime object and then associating it with the desired timezone. To achieve this, you can use the datetime module in Python. Here’s a step-by-step guide:

  • First, import the necessary classes from the datetime module. You will need the datetime class itself, along with the timezone and timedelta classes.
from datetime import datetime, timezone, timedelta
  • Before converting the string to a datetime object, you need to understand its format. This is important because you will need to inform Python how to interpret the string.
  • ‘%Y-%m-%d’ for “2023-06-18”
  • ‘%Y-%m-%d %H:%M:%S’ for “2023-06-18 15:30:20”
  • You can use the strptime method from the datetime class to convert the string into a datetime object. strptime stands for “string parse time”, and it requires two arguments: the string and its format.
date_string = "2023-06-18 15:30:20" format_string = "%Y-%m-%d %H:%M:%S" datetime_object = datetime.strptime(date_string, format_string)
  • If the string you’re parsing includes timezone information, Python will automatically parse this as well. If not, you can associate a timezone manually. To associate a timezone manually, use the replace method to attach a timezone. Here’s how you can do it:
# Associating a UTC timezone datetime_in_utc = datetime_object.replace(tzinfo=timezone.utc) # Associating a timezone with an offset (e.g., UTC+5:30) offset = timezone(timedelta(hours=5, minutes=30)) datetime_with_offset = datetime_object.replace(tzinfo=offset)
date_string_with_timezone = "2023-06-18 15:30:20+05:30" format_string_with_timezone = "%Y-%m-%d %H:%M:%S%z" datetime_with_timezone = datetime.strptime(date_string_with_timezone, format_string_with_timezone)
from datetime import datetime, timezone, timedelta # String without timezone information date_string = "2023-06-18 15:30:20" format_string = "%Y-%m-%d %H:%M:%S" datetime_object = datetime.strptime(date_string, format_string) # Associating a timezone with an offset (e.g., UTC+5:30) offset = timezone(timedelta(hours=5, minutes=30)) datetime_with_offset = datetime_object.replace(tzinfo=offset) print(datetime_with_offset) # String with timezone information date_string_with_timezone = "2023-06-18 15:30:20+05:30" format_string_with_timezone = "%Y-%m-%d %H:%M:%S%z" datetime_with_timezone = datetime.strptime(date_string_with_timezone, format_string_with_timezone) print(datetime_with_timezone)

This code demonstrates how to convert a string to a datetime object and associate it with timezone information in Python. You can check out the below output:

python convert string to datetime with timezone

Convert a string to datetime with milliseconds in Python

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.

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:

python convert string to datetime with timezone

Convert a string to datetime iso format in Python

Here, we can see how to convert 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.

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:

convert utc string to datetime python

Convert a string to datetime yyyy-mm-dd in Python

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.
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:

convert string to datetime with timezone python

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 the 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.
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

You may like the following Python tutorials:

This Python tutorial explains, how to convert string to datetime with timezone in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Читайте также:  Http do cdodd ru mod page view php id 4503
Оцените статью