程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python datetime module

編輯:Python

python datetime modular

List of articles

  • 1. Get the current time
  • 2. The time interval timedelta
  • 3. datetime turn character string strftime()
  • 4. character string turn datetime object datetime.strptime()
  • 5. parse() Parse string date

Guide pack

from datetime import datetime

1. Get the current time

now = datetime.now()
print(now)
print(type(now))
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)


2. The time interval timedelta

from datetime import timedelta

Two datetime Object subtraction , What you get is a timedelta object

# Calculate the time interval 
delta1 = datetime(2022, 6, 30, 20) - datetime(2022, 2, 2, 1)
print(delta1)
print(type(delta1))


Pictured , Express 148 Tianzero 19 Hours .


print(datetime(2022, 6, 10) + delta1)


timedelta Pass in a different number of parameters , The meaning of the expression is summarized as follows .

The first represents the number of days , The second represents the number of seconds , The third represents microseconds . The fourth represents milliseconds , The fifth represents minutes , The sixth represents the hour .

print(timedelta(10))
print(timedelta(10,11))
print(timedelta(10, 11, 12))
print(timedelta(10, 11, 12, 13))
print(timedelta(10, 11, 12, 13, 14))
print(timedelta(10, 11, 12, 13, 14, 15))


3. datetime turn character string strftime()

stamp = datetime(2022, 6, 22)
# Cast string 
print(str(stamp))
# format transformation character string 
print(stamp.strftime("%Y/%m/%d %H:%M:%S"))
print(stamp.strftime("%Y-%m-%d %H:%M:%S"))
print(stamp.strftime("%Y/%m/%d"))
print(stamp.strftime("%Y-%m-%d"))


4. character string turn datetime object datetime.strptime()

dates = ['1/6/2022', '6/1/2022']
datelist = [datetime.strptime(i, "%m/%d/%Y") for i in dates]
print(datelist)


5. parse() Parse string date

Parses a date in the form of a string into datetime object .
There are many ways to write strings , The following example .

from dateutil.parser import parse
print(parse('1/6/2022'))
print(parse('2022-6-2'))
print(parse('2022.6.3'))
print(parse('2022 6 4'))
print(parse('2022, 6, 5'))


꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ꧔ꦿ
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved