Python datetime from isoformat

Python ISO 8601 Datetime

In this article, you’ll learn how to work with ISO 8601 datetime in Python.

After reading this Python article, you’ll learn:

  • How to get current ISO 8601 datetime in Python.
  • How to convert the existing datetime to ISO 8601 time format.
  • Also, datetime can contain timezone information i will show you how to convert datetime with timezone information to ISO 8601 format.
  • Also, I will show you how to convert UTC to ISO 8601 format.

Table of contents

What is the Format of ISO 8601 Datetime in Python

The first question is, what is ISO time?

ISO 8601 is an internationally agreed way to represent dates. (YYYY-MM-DD). ISO 8601 can be used by anyone who wants to use a standardized way of presenting datetime, UTC, and local time with offset to UTC.

Format of ISO 8601 Date:

In Python ISO 8601 date is represented in YYYY-MM-DDTHH:MM:SS.mmmmmm format. For example, May 18, 2022, is represented as 2022-05-18T11:40:22.519222.

  • YYYY: Year in four-digit format
  • MM: Months from 1-12
  • DD: Days from 1 to 31
  • T: It is the separator character that is to be printed between the date and time fields. It is an optional parameter having a default value of “T”.
  • HH: For the value of minutes
  • MM: For the specified value of minutes
  • SS: For the specified value of seconds
  • mmmmmm: For the specified microseconds

How to get ISO 8601 Datetime in Python

There can be scenarios where you want to get the current ISO 8601 datetime. Also, you may need to convert the existing datetime to an ISO 8601 format. we’ll cover both the cases. The below steps show how to convert datetime to ISO 8601 date in string format in Python.

  1. Import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
  2. Get Current Datetime If you want to get the current ISO 8601 datetime first, you need to get the current datetime using the datetime.now() function. If you already have a datetime object, you can skip this step.
  3. Use the isoformat() method To convert datetime to ISO 8601 format use the isoformat() method. It returns a string representing the date in ISO 8601 format. this ISO string contains the date, time, and UTC offset to the corresponding time zone.
Читайте также:  Python try except sqlite

Example 1: Get Current ISO 8601 Datetime

from datetime import datetime # get current datetime today = datetime.now() print('Today Datetime:', today) # Get current ISO 8601 datetime in string format iso_date = today.isoformat() print('ISO DateTime:', iso_date)
Today Datetime: 2022-05-18 12:19:51.685496 ISO DateTime: 2022-05-18T12:19:51.685496

Refer to the below code if you want to change the separator between date and time.

from datetime import datetime iso_date = datetime.now().isoformat('#') print(iso_date) # output # 2022-05-18#12:43:02.430554

Example 2: Convert Datetime to ISO 8601 format

If you have input datetime object, you can use the below example to convert it to ISO 8601 format. Also if you have datetime in a string format then first convert string to datetime.

from datetime import datetime dt = datetime(2021, 10, 24, 8, 48, 34, 685496) print('Input Datetime:', dt) # convert datetime to ISO date iso_date = dt.isoformat() print('ISO Date:', iso_date)
Input Datetime: 2021-10-24 08:48:34.685496 ISO Date: 2021-10-24T08:48:34.685496

Convert Datetime with TimeZone information to ISO 8601

A time zone represents the standardized time depending on which part of the world is being considered. For example, CT(Central Time) in North and South America is either 5 or 6 hours behind and represented as UTC-5 or UTC-6 based on the Day Light Saving.

In Python, a date object can be mentioned with or without time zones. Based on that, an object is known as Naive or Aware. A date object, by default, is naive. A datetime or time object is aware if it holds the timezone value. See the timezone in Python for more detail.

For example, The datetime.now() function returns the current local datetime without any timezone information. Using the pytz library, we can pass the timezone name to this function to get the current datetime in the given timezone.

Читайте также:  Удаляем символы кавычек php

In the below Python example we’ll see how to convert datetime with timezone information to the ISO 8601 date format.

from datetime import datetime import pytz # current Datetime # US/Central timezone datetime aware_us_central = datetime.now(pytz.timezone('US/Central')) print('US Central DateTime', aware_us_central) # timezone aware datetime to ISO 8601 date iso_date = aware_us_central.isoformat() print('ISO Datetime', iso_date)
US Central DateTime 2022-05-18 03:08:36.233201-05:00 ISO Datetime 2022-05-18T03:08:36.233201-05:00

Note: -05:00 is the UTC Offset for the US/Central timezone.

Get current isoformat datetime string including the default timezone

  • Get current datetime using the now() function
  • Next, Add default timezone information to datetime using the astimezone() function. The local timezone or default is your system’s timezone information.
  • In the end, use the isoformat() method to get the current isoformat datetime string including the default timezone.
from datetime import datetime, timezone # get current datetime in UTC dt = datetime.now(timezone.utc) # add local timezone information to datetime tz_dt = dt.astimezone() print('current datetime with local timezone:', tz_dt) # Get current iso 8601 format datetime string including the default timezone iso_date = tz_dt.isoformat() print('ISO datetime with local timezone:', iso_date)
current datetime with local timezone: 2022-05-18 14:26:07.827208+05:30 ISO datetime with local timezone: 2022-05-18T14:26:07.827208+05:30

Note: +05.30 is a Indian timezone (IST) of my machine. You’ll get a different result depending on your system’s timezone.

UTC to ISO 8601 in Python

UTC – Coordinated Universal Time is the common time standard across the world. So, in Python, to work with the timezone without any issues, it is recommended to use the UTC as your base timezone.

In this example, we’ll see how to convert the UTC date to the ISO 8601 date in Python.

  • First, get the current UTC datetime by mentioning the timezone.utc attribute in the now() function.
  • Next, use the isoformat() method convert the UTC time to ISO 8601 format.
from datetime import datetime, timezone # get current datetime in UTC utc_dt = datetime.now(timezone.utc) print('UTC time:', utc_dt) # convert UTC time to ISO 8601 format iso_date = utc_dt.isoformat() print('ISO datetime:', iso_date)
UTC time: 2022-05-18 09:32:28.779252+00:00 ISO datetime: 2022-05-18T09:32:28.779252+00:00

Note: The offset at the end is +00:00 which is the standrad UTC offset.

Читайте также:  Learn Jquery Css Method

UTC to ISO 8601 with local timezone information without a microsecond

  • Import datetime class from a datetime module
  • Next, get the current datetime using the now() function
  • Next, use the astimezone() to add the local timezone information to a datetime object.
  • In the end, use the isoformat() method to convert the UTC to ISO 8601 with local timezone information.
from datetime import datetime, timezone # get current datetime in UTC utc_dt = datetime.now(timezone.utc) print('UTC time:', utc_dt) # convert UTC time to ISO 8601 format iso_date = utc_dt.astimezone().isoformat() print('ISO datetime:', iso_date)
ISO datetime: 2022-05-18T13:56:41+05:30

Local Datetime to ISO 8601 without microsecond

local time is your system’s datetime. For example, The datetime.now( ) function returns the current local datetime without any timezone information.

Use the replace() function of a datetime module to remove the microseconds component from the datetime object. Let’s see how to convert local datetime to ISO 8601 without the microseconds component.

from datetime import datetime import pytz # local datetime to ISO Datetime iso_date = datetime.now().replace(microsecond=0).isoformat() print('ISO Datetime:', iso_date)
ISO Datetime: 2022-05-18T13:43:13

Local to ISO 8601 with TimeZone information

from datetime import datetime # get local time dt = datetime.now() # convert local datetime to ISO 8601 with TimeZone information iso_date = dt.astimezone().isoformat() print('ISO datetime with local timezone:', iso_date)
ISO datetime with local timezone: 2022-05-18T14:08:08.080091+05:30

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью