Home > Backend Development > Python Tutorial > A brief discussion on using the datetime package to perform some time operations in Python

A brief discussion on using the datetime package to perform some time operations in Python

WBOY
Release: 2016-07-06 13:29:54
Original
1255 people have browsed it

1. Calculate the time difference between two given times

import datetime as dt
# current time
cur_time = dt.datetime.today()
# one day
pre_time = dt.date(2016, 5, 20) # eg: 2016.5.20
delta = cur_time - pre_time
# if you want to get discrepancy in days
print delta.days
# if you want to get discrepancy in hours
print delta.hours
# and so on
Copy after login

2. Get the time n days ago

cur_time = dt.now()
# previous n days
pre_time = dt.timedelta(days=n)
Copy after login

3. Accurate the given time to days or other units

cur_time = dt.now()
# get day of current time
cur_day = cur_time.replace(hour=0, minute=0, second=0, mircrosecond=0)
Copy after login

4. Get a series of time series (return list)

cur_time = dt.datetime.today()
datelist = [cur_time - dt.timedelta(days=x) for x in range(0, 100)]
Copy after login

or

import pandas as pd
datelist = pd.date_range(pd.datetime.today(), periods=100).tolist()
Copy after login

5. Convert time string to datetime type

date_formate = "%Y-%m-%d" # year-month-day
time = dt.strptime('2016-06-22', date_format)
Copy after login

6. Convert time type to string type

time_str = dt.strftime("%Y-%m-%d", dt.now()) # return like "2016-06-22"
Copy after login

The above is the complete content of the editor’s brief discussion on using the datetime package to perform some time operations in Python. I hope you will support Script Home~

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