python date, time, string conversion (reproduced)

Original link: https://www.cnblogs.com/huhu-xiaomaomi/p/10338472.html

In python, date and date type datetime type dateTime is not comparable.

(1) To compare, may be converted to a dateTime date, date can not be converted directly 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

(2) the date of type date into a 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 'datetime.date'>
print(str_p,type(str_p)) #2019-01-30 <class 'str'>

(3) is converted to a string type str type dateTime

import datetime
str_p = "30/01/2019 15:29:08"
dateTime_p = datetime.datetime.strptime(str_p,'%Y-%m-%d %H:%M:%S')
print(dateTime_p) # 2019-01-30 15:29:08

(4) dateTime type into str type

  This place I do not understand why the format specified is invalid

import datetime
dateTime_p = datetime.datetime.now()
str_p = datetime.datetime.strftime(dateTime_p,'%Y-%m-%d')
print(dateTime_p) # 2019-01-30 15:36:19.415157

(5) a string type to convert a date type str

#!/usr/bin/env python3
import datetime
str_p = "01/30/2019"
date_p = datetime.datetime.strptime(str_p,'%Y-%m-%d').date()
print(date_p,type(date_p)) # 2019-01-30 <class 'datetime.date'>

Also type and date dateTime type can do this directly add 1 subtract operation 1

Copy the code
#!/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

Guess you like

Origin www.cnblogs.com/xibuhaohao/p/12071231.html