How to convert string into time

anonymity
Release: 2019-05-25 16:13:43
Original
28976 people have browsed it

In python, convert dates, times, and strings to each other.

How to convert string into time

(1) DateTime can be converted to date, but date cannot be directly converted to dateTime

import datetime
dateTime_p = datetime.datetime.now()  
date_p = dateTime_p.date() 
print(dateTime_p) #2019-01-30 15:17:46.573139
print(date_p) #2019-01-30
Copy after login

(2) Date type date is converted to string str

#!/usr/bin/env python3
import datetime
date_p = datetime.datetime.now().date()
str_p = str(date_p)
print(date_p,type(date_p)) #2019-01-30 <class &#39;datetime.date&#39;>
print(str_p,type(str_p)) #2019-01-30 <class &#39;str&#39;>
Copy after login

(3) Convert string type str to dateTime type

import datetime
str_p = &#39;2019-01-30 15:29:08&#39;
dateTime_p = datetime.datetime.strptime(str_p,&#39;%Y-%m-%d %H:%M:%S&#39;)
print(dateTime_p) # 2019-01-30 15:29:08
Copy after login

(4) Convert dateTime type to str type

import datetime
dateTime_p = datetime.datetime.now()
str_p = datetime.datetime.strftime(dateTime_p,&#39;%Y-%m-%d&#39;)
print(dateTime_p) # 2019-01-30 15:36:19.415157
Copy after login

(5) Convert string type str to date Type

#!/usr/bin/env python3
import datetime
str_p = &#39;2019-01-30&#39;
date_p = datetime.datetime.strptime(str_p,&#39;%Y-%m-%d&#39;).date()
print(date_p,type(date_p)) # 2019-01-30 <class &#39;datetime.date&#39;>
Copy after login

In addition, the dateTime type and date type can directly perform operations such as adding 1 and subtracting 1

#!/usr/bin/env python3
import datetime
# today = datetime.datetime.today()
today = datetime.datetime.today().date()
yestoday = today + datetime.timedelta(days=-1)
tomorrow = today + datetime.timedelta(days=1)
print(today) # 2019-01-30
print(yestoday)# 2019-01-29
print(tomorrow)# 2019-01-31
Copy after login

The above is the detailed content of How to convert string into time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template