发布网友 发布时间:2022-04-24 15:36
共2个回答
热心网友 时间:2022-04-07 06:25
用Python实现字符串和日期相互转换的方法,具体如下:
这里用的分别是time和datetime函数来处理
import
time,datetime//日期转化为字符串#
date
to
str//输出时间print
time.strftime("%Y-%m-%d
%X",
time.localtime())#str
to
date//字符串转化为日期t
=
time.strptime("2016
-
12
-
05",
"%Y
-
%m
-
%d")y,m,d
=
t[0:3]//输出时间print
datetime.datetime(y,m,d)
热心网友 时间:2022-04-07 07:43
python中要把字符串转换成日期格式需要使用time模块中的strptime函数,例子如下:
import time
t = time.strptime('2016-05-09 21:09:30', '%y-%m-%d %h:%m:%s')
print(t)执行结果如下:
time.struct_time(tm_year=2016,
tm_mon=5,
tm_mday=9,
tm_hour=21,
tm_min=9,
tm_sec=30,
tm_wday=0,
tm_yday=130,
tm_isdst=-1)
函数说明:
第一个参数是要转换成日期格式的字符串,第二个参数是字符串的格式
函数官方文档如下:
help on built-in function strptime in mole time:
strptime(...)
strptime(string, format) -> struct_time
parse a string to a time tuple according to a format specification.
see the library reference manual for formatting codes (same as
strftime()).
commonly used format codes:
%y year with century as a decimal number.
%m month as a decimal number [01,12].
%d day of the month as a decimal number [01,31].
%h hour (24-hour clock) as a decimal number [00,23].
%m minute as a decimal number [00,59].
%s second as a decimal number [00,61].
%z time zone offset from utc.
%a locale's abbreviated weekday name.
%a locale's full weekday name.
%b locale's abbreviated month name.
%b locale's full month name.
%c locale's appropriate date and time representation.
%i hour (12-hour clock) as a decimal number [01,12].
%p locale's equivalent of either am or pm.
other codes may be available on your platform. see documentation for the c library strftime function.