如何在Python以毫秒为单位使用 strptime
Python的strptime()函数将字符串转换为 DateTime 对象。 strptime() 是一个类方法,它接受两个参数:
- 应转换为日期时间对象的字符串
- 格式字符串用来解析字符串。
这两个字符串参数对于将字符串转换为 DateTime 对象是必需的。
句法:
strptime(date_string, format_string)
格式代码列表:
Format string | Interpretation | Example |
---|---|---|
%a | Weekday as an abbreviated name. | Sun, Mon, …, Sat |
%A | Weekday as full name. | Sunday, Monday, …, Saturday |
%w | Weekday as a decimal number, 0 is Sunday and 6 is Saturday. | 0, 1, …, 6 |
%d | Day of the month as a zero-padded decimal number. | 01, 02, …, 31 |
%b | Month as an abbreviated name. | Jan, Feb, …, Dec |
%B | Month. | January, February, …, December |
%m | Month | 01, 02, …, 12 |
%y | Year without century. | 00, 01, …, 99 |
%Y | Year with century. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 |
%H | Hour (24-hour clock). | 00, 01, …, 23 |
%I | Hour (12-hour clock). | 01, 02, …, 12 |
%p | either AM or PM. | AM, PM |
%M | Minute. | 00, 01, …, 59 |
%S | Second. | 00, 01, …, 59 |
%f | Microsecond as a decimal number. | 000000, 000001, …, 999999 |
%z | UTC offset in the form ±HHMM[SS[.ffffff]] . | +0000, -0400, +1030, +063415, -030712.345216 |
%Z | Time zone (UTC, GMT) | |
%j | Day of the year. | 001, 002, …, 366 |
%U | Week number of the year (Sunday as the first day of the week). | 00, 01, …, 53 |
%W | Week number of the year (Monday as the first day of the week) as a decimal number. | 00, 01, …, 53 |
%c | preferred date and time representation. | Tue Aug 16 21:30:00 1998 |
%x | preferred date representation. | 08/16/88 08/16/1998 |
%X | preferred 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