python datetime.datetime, datetime.date, datetime.timedelt time processing

python datetime.datetime, datetime.date, datetime.timedelt time processing

datetime The main objects for processing date and time:
    timedelt: date difference or time difference (commonly used)
    datetime: time and date (commonly used)
    date: date
    time: time

1、datetime.datetime / datetime.date

(1) Get the current date and time: (Return result: datetime.datetime(2020, 9, 23, 16, 6, 28, 491179))

import datetime as dt
dt.datetime.now() 
dt.datetime.today() 

(2) Get the current date: (Return result: datetime.date(2020, 9, 23))

dt.date.today() 
dt.datetime.now().date()
dt.datetime.today().date()

(3) Get the year in the date: (return result: 2020)

dt.datetime(2020,9,23).year
dt.date(2020,9,23).year

(4) Get the month in the date: (return result: 9)

dt.datetime(2020,9,23).month
dt.date(2020,9,23).month

(5) Get the number of dates in the date: (return result: 23)

dt.datetime(2020,9,23).day
dt.date(2020,9,23).day

(6) What day of the week is the acquisition date:

dt.datetime(2020,9,23).isoweekday()  # (返回结果:3)1-7 对应 周一 - 周日
dt.date(2020,9,23).weekday()  # (返回结果:2)0-6 对应 周一 - 到周日

(7) Time zone:

  • The difference between now and utcnow:
        now: local time
        utcnow: world time (because the time zone is different, the two times are different)

  • "Asia/Shanghai" current time is '2020-09-23 16:20:25', which is converted to "Asia/Kolkata" time

    import pytz    
    dt_in = dt.datetime(2020, 9, 23, 16, 20, 25, tzinfo = pytz.timezone('Asia/Shanghai'))
    dt_in.astimezone(pytz.timezone('Asia/Kolkata'))
    # 返回结果:datetime.datetime(2020, 9, 23, 13, 44, 25, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
    

    Note: View the code corresponding to the time zone: pytz.all_timezones

2 、 datetime.timedelt

    timedelt is often used for time difference, its parameters include:
        weeks, days (default), hours, minutes, seconds, microseconds
        (for details, see: python date plus days, weeks, hours timedelta )

Guess you like

Origin blog.csdn.net/weixin_40012554/article/details/108750259