The Wayback Machine - https://web.archive.org/web/20240712004447/https://www.geeksforgeeks.org/parsing-datetime-strings-containing-nanoseconds-in-python/
Open In App

Parsing DateTime strings containing microseconds in Python

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that have microseconds in them. Python has a list of directives that can be used in order to parse the strings as datetime objects. Let us have a look at some of them that we will be using in our codes.

Directive Description Example
%Y Year 2021
%m Month Number 7
%d Date of the month 5
%H 24 Hour format 16
%M Minute 51
%f Microsecond 234567

Image Demonstration of DateTime object:

Demonstration of DateTime object

Demonstration of DateTime object

Let us take the default Python timestamp format: “2021-08-05 15:25:56.792554” as an example to work on.

Method 1: Using DateTime module

In this example, we will see that the microseconds value is 792554. “%f” directive is used to parse the microseconds. The same thing is cross-verified by converting the “%f” directive to the string value of its representation for the datetime object using the strftime() method.

Python




from datetime import datetime
 
# Parse the default python timestamp format
dt_obj = datetime.strptime("2021-08-05 15:25:56.792554",
                           "%Y-%m-%d %H:%M:%S.%f")
 
# Verify the value for nano seconds
nano_secs = dt_obj.strftime("%f")
 
# Print the value of nano seconds
print(nano_secs)


Output

792554

Method 2: Using Pandas library

Here we will use pandas.to_datetime() methods to parsing DateTime strings containing microseconds.

Syntax:

pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)

 Parameters:

arg: An integer, string, float, list or dict object to convert in to Date time object.
dayfirst: Boolean value, places day first if True.
yearfirst: Boolean value, places year first if True.
utc: Boolean value, Returns time in UTC if True.
format: String input to tell position of day, month and year.

Python




import pandas as pd
 
# Parse the timestamp string by
# providing the format of timestamp string
dt_obj = pd.to_datetime("2021-08-05 15:25:56.792554",
                        format="%Y-%m-%d %H:%M:%S.%f")
 
# Verify the value for nano seconds
nano_secs = dt_obj.strftime("%f")
 
# Print the value of nano seconds
print(nano_secs)


Output:

792554

The above example is similar to the earlier one except for the fact that we have used pandas library instead of the datetime module. This can prove to be handy when we are working with pandas dataframes. One beautiful thing about this library is that we might not need to provide the format manually. The parameter infer_datetime_format in the pandas.to_datetime() method can take care of that automatically if provided as True. In cases, it can increase the parsing speed by ~5-10x. Below is an example of the same.

Python




import pandas as pd
 
# Parse the timestamp string by
# providing infer_datetime_format as True
dt_obj = pd.to_datetime("2021-08-05 15:25:56.792554",
                        infer_datetime_format=True)
 
# Verify the value for nano seconds
nano_secs = dt_obj.strftime("%f")
 
# Print the value of nano seconds
print(nano_secs)


Output:

792554


Similar Reads

Python | Pandas TimedeltaIndex.microseconds
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.microseconds attribute return the number of microseconds for each element in the TimedeltaIndex object. The value
2 min read
Python | Pandas Timedelta.microseconds
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Parsing XML with DOM APIs in Python
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as bel
2 min read
Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By buildin
4 min read
Parsing PDFs in Python with Tika
Apache Tika is a library that is used for document type detection and content extraction from various file formats. Using this, one can develop a universal type detector and content extractor to extract both structured text and metadata from different types of documents such as spreadsheets, text documents, images, PDF's, and even multimedia input
2 min read
Parsing and Processing URL using Python - Regex
Prerequisite: Regular Expression in Python URL or Uniform Resource Locator consists of many information parts, such as the domain name, path, port number etc. Any URL can be processed and parsed using Regular Expression. So for using Regular Expression we have to use re library in Python. Example: URL: https://www.geeksforgeeks.org/courses When we
3 min read
Parsing and converting HTML documents to XML format using Python
In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module.Using Beautifulsoup module.Method 1: Using the Python lxml library In this approach, we will use Python's lxml library to parse the HTML document and write it to an encoded string representation of
3 min read
three90RightbarBannerImg