📜  如何在Python以毫秒为单位使用 strptime

📅  最后修改于: 2022-05-13 01:54:46.479000             🧑  作者: Mango

如何在Python以毫秒为单位使用 strptime

Python的strptime()函数将字符串转换为 DateTime 对象。 strptime() 是一个类方法,它接受两个参数:

  • 应转换为日期时间对象的字符串
  • 格式字符串用来解析字符串。

这两个字符串参数对于将字符串转换为 DateTime 对象是必需的。

句法:

格式代码列表:



Format stringInterpretationExample
%a Weekday as an abbreviated name.Sun, Mon, …, Sat 
%AWeekday as full name.Sunday, Monday, …, Saturday 
%wWeekday as a decimal number, 0 is Sunday and 6 is Saturday.0, 1, …, 6
%dDay of the month as a zero-padded decimal number.01, 02, …, 31
%bMonth as an abbreviated name.Jan, Feb, …, Dec
%BMonth.January, February, …, December
%mMonth01, 02, …, 12
%yYear without century.00, 01, …, 99
%YYear with century.0001, 0002, …, 2013, 2014, …, 9998, 9999
%HHour (24-hour clock).00, 01, …, 23
%IHour (12-hour clock).01, 02, …, 12
%peither AM or PM.AM, PM
%MMinute.00, 01, …, 59
%SSecond.00, 01, …, 59
%f Microsecond as a decimal number.000000, 000001, …, 999999
%zUTC offset in the form ±HHMM[SS[.ffffff]] .+0000, -0400, +1030, +063415, -030712.345216
%ZTime zone (UTC, GMT) 
%jDay of the year.001, 002, …, 366
%UWeek number of the year (Sunday as the first day of the week). 00, 01, …, 53
%WWeek number of the year (Monday as the first day of the week) as a decimal number. 00, 01, …, 53
%cpreferred date and time representation.Tue Aug 16 21:30:00 1998
%x preferred date representation.

08/16/88

08/16/1998

%Xpreferred time representation.

21:30:00

%% – A literal ‘%’ character.

要使用此函数在Python生成毫秒 %f 用于格式代码。

下面给出了一些实现。

示例 1:以毫秒为单位的时间

Python3
from datetime import datetime
  
datetime_string = "15/06/2021 13:30:15.120"
  
print(type(datetime_string))
  
format = "%d/%m/%Y %H:%M:%S.%f"
  
# converting datetime string to datetime 
# object with milliseconds..
date_object = datetime.strptime(datetime_string, format)
  
print("date_object =", date_object)
  
# Type is datetime object
print(type(date_object))


Python3
from datetime import datetime
  
# Getting current datetime and converting
# it to string
date_str = str(datetime.now())
  
print(type(date_str))
  
print(datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f'))


Python3
from datetime import datetime
  
# Using strptime() with milliseconds
  
date_time = datetime.strptime(
    "17 Oct 2021 15:48:35.525001", "%d %b %Y %H:%M:%S.%f")
  
print(date_time)


输出:


date_object = 2021-06-15 13:30:15.120000

示例 2:以毫秒为单位的时间

蟒蛇3

from datetime import datetime
  
# Getting current datetime and converting
# it to string
date_str = str(datetime.now())
  
print(type(date_str))
  
print(datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f'))

输出:


2021-08-01 15:27:59.979673

示例 3:以毫秒为单位的时间

蟒蛇3

from datetime import datetime
  
# Using strptime() with milliseconds
  
date_time = datetime.strptime(
    "17 Oct 2021 15:48:35.525001", "%d %b %Y %H:%M:%S.%f")
  
print(date_time)

输出:

2021-10-17 15:48:35.525001