在Python中解析含有纳秒的DateTime字符串

在Python中解析含有纳秒的DateTime字符串

大多数应用要求的精度可达几秒钟,但也有一些关键的应用要求纳秒级的精度,特别是那些可以进行极速计算的应用。它可以帮助深入了解与应用程序的时间空间有关的某些因素。让我们看看如何能解析含有纳秒的DateTime字符串。Python有一个指令列表,可以用来将字符串解析为日期时间对象。让我们看一下我们将在代码中使用的其中一些指令。

指令 描述 例子
%Y 年份 2021
%m 月号 7
%d 月份的日期 5
%H 24小时格式 16
%M 分钟 51
%f 微秒 234567

DateTime对象的图像演示

在Python中解析含有纳秒的DateTime字符串

剖析的图像表示

让我们以默认的Python时间戳格式。”2021-08-05 15:25:56.792554 “作为一个例子来工作。

方法1:使用DateTime模块

在这个例子中,我们将看到纳秒的值是792554。” %f _ ” 指令被用来解析纳秒。通过使用_strftime()方法将”_%f _”指令转换为其表示日期时间对象的字符串值,可以交叉验证同样的事情。

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)

输出

792554

方法2:使用Pandas库

这里我们将使用pandas.to_datetime()方法来解析包含纳秒的DateTime字符串。

语法:

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

参数:

  • arg: 一个整数、字符串、浮点数、列表或dict对象,用于转换为Date时间对象。
  • dayfirst: 布尔值,如果为真,则将日期放在首位。
  • yearfirst: 布尔值,如果为真,将年份放在前面。
  • utc:布尔值,如果为真,则返回UTC的时间。
  • format:字符串输入,告诉日、月、年的位置。
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)

输出:

792554

上面的例子与前面的例子类似,只是我们使用了pandas库而不是datetime模块。当我们在使用pandas数据框架时,这可以证明是很方便的。这个库的一个好处是,我们可能不需要手动提供格式。在pandas.to_datetime()方法中的参数infer_datetime_format可以自动处理这个问题,如果提供的是True。在某些情况下,它可以将解析速度提高~5-10倍_。下面是一个相同的例子。

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)

输出:

792554

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程