Python get current date and date difference calculation

Posted by trace on Sun, 01 Dec 2019 14:53:34 +0100

Getting date and time in Python is very simple, mainly using time and datetime packages

1. Get the current time and format it

from dateutil import rrule
from datetime import datetime
import time


#Get date, format yyyy-mm-dd hh:mm:ss
#The first way
strtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(strtime)
print(type(strtime))
#Output: 2019-01-08 16:44:08
#Output:<class 'str'>

#The second way
now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S'))
#Output: 2019-01-08 16:44:08

As you can see, strftime converts a time object to str.

2. str transfer date

from dateutil import rrule
from datetime import datetime
import time

#str Date of transfer
#The first way
initDate = datetime.strptime('2019-01-09 10:11:11','%Y-%m-%d %H:%M:%S')
print(initDate)
print(type(initDate))
#Output: 2019-01-09 10:11:11
#     <class 'datetime.datetime'>

#The second way
secondDate = time.strptime('2019-01-09 10:11:11','%Y-%m-%d %H:%M:%S')
print(secondDate)
print(type(secondDate))
#Output: time.struct_time(tm_year=2019, tm_mon=1, tm_mday=9, tm_hour=10, tm_min=11, tm_sec=11, tm_wday=2, tm_yday=9, tm_isdst=-1)
#     class 'time.struct_time'>

 

3. Date time difference

from dateutil import rrule
from datetime import datetime
import time

#Calculate date difference
untilYear = 2018
untilMonth = 5
untilDay = 1

# 2018 First day of the year
firstDay = datetime(untilYear,1,1)
endDay = datetime(untilYear,untilMonth,untilDay)

#rrule.DAILY Calculate the difference between days and weeks(WEEKLY),Year ( YEARLY)
days = rrule.rrule(freq = rrule.DAILY,dtstart=firstDay,until=endDay)

print('Differ:',days.count(),'day')

Here we mainly use the rrule of dateutil.

 

There are many ways to use python's date and time. Here, you can only record the parts you use more often. Later, you can learn the time stamp.

 

Python version: 3.7

Reference documents:

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

https://dateutil.readthedocs.io/en/stable/rrule.html#rrule-examples

Topics: Python