python datatime string and date conversion


Preface

In order to achieve the function of converting string to date, this article specially writes a blog post for next time use.


1. Datatime date format

Time and date formatting symbols in python:

%y two-digit year

%Y four-digit year

%m month

%d days

%H 24-hour hour

%I hour in 12-hour format

%M minutes

%S seconds

%j Day within the year (001-366)

Generally: '%Y-%m-%d-%H-%M-%S' represents 2022-06-17-16-55-35

2. Usage steps


from datetime import datetime
import time

date_string = '2001-06-17-00-00-00'
date_string2 = '2022-06-15-15-45-16'
#字符串转时间
date_object = datetime.strptime(date_string, '%Y-%m-%d-%H-%M-%S')
date_object2 = datetime.strptime(date_string2, '%Y-%m-%d-%H-%M-%S')
sub_time=date_object2-date_object
#获得两个时间相差秒数
print(sub_time.seconds)

#把其中一个时间前进20S
date_object=datetime.fromtimestamp( int(time.mktime(date_object.timetuple()))+20)
sub_time=date_object2-date_object
print(sub_time)
print(sub_time.seconds)


#还有一个时间转字符串的
print(date_object.strftime("%Y-%m-%d-%H-%M-%S"))


Summarize

Just write it down, make do with it, and continue to add more when you encounter other ones later.

Guess you like

Origin blog.csdn.net/qq_55542491/article/details/125355418