一、使用 time 模块展示当前日期和时间
import time
from time import gmtime, strftime
t = time.localtime()
print (time.asctime(t))
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))
print(strftime("%A", gmtime()))
print(strftime("%D", gmtime()))
print(strftime("%B", gmtime()))
print(strftime("%y", gmtime()))
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))
二、将天、小时、分钟转换为秒
SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400
days = int(input("Enter number of Days: "))
hours = int(input("Enter number of Hours: "))
minutes = int(input("Enter number of Minutes: "))
seconds = int(input("Enter number of Seconds: "))
total_seconds = days * SECONDS_PER_DAY
total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)
total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)
total_seconds = total_seconds + seconds
print("Total number of seconds: ","%d"%(total_seconds))
'''
Enter number of Days: 5
Enter number of Hours: 36
Enter number of Minutes: 24
Enter number of Seconds: 15
Total number of seconds: 563055
'''
三、使用 Pandas 获取当前日期和时间
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
四、将字符串转换为日期时间对象
from datetime import datetime
from dateutil import parser
d1 = "Jan 7 2015 1:15PM"
d2 = "2015 Jan 7 1:33PM"
date1 = datetime.strptime(d1, '%b %d %Y %I:%M%p')
print(type(date1))
print(date1)
date2 = parser.parse(d2)
print(type(date2))
print(date2)
五、以毫秒为单位获取当前时间
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)
六、以 MST、EST、UTC、GMT 和 HST 获取当前日期时间
from datetime import datetime
from pytz import timezone
mst = timezone('MST')
print("Time in MST:", datetime.now(mst))
est = timezone('EST')
print("Time in EST:", datetime.now(est))
utc = timezone('UTC')
print("Time in UTC:", datetime.now(utc))
gmt = timezone('GMT')
print("Time in GMT:", datetime.now(gmt))
hst = timezone('HST')
print("Time in HST:", datetime.now(hst))
七、从给定的日期当中获取星期几
import datetime
dayofweek = datetime.date(2010, 6, 16).strftime("%A")
print(dayofweek)
print("weekday():", datetime.date(2010, 6, 16).weekday())
print("isoweekday()", datetime.date(2010, 6, 16).isoweekday())
dayofweek = datetime.datetime.today().strftime("%A")
print(dayofweek)
print("weekday():", datetime.datetime.today().weekday())
print("isoweekday()", datetime.datetime.today().isoweekday())
八、计算两个日期时间对象之间的时差
import datetime
from datetime import timedelta
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
date1 = '2016-04-16 10:01:28.585'
date2 = '2016-03-10 09:56:28.067'
diff = datetime.datetime.strptime(date1, datetimeFormat)\
- datetime.datetime.strptime(date2, datetimeFormat)
print("Difference:", diff)
print("Days:", diff.days)
print("Microseconds:", diff.microseconds)
print("Seconds:", diff.seconds)
九、将 5 分钟添加到 Unix 时间戳
import datetime
import calendar
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple()))
十、遍历一系列日期
import datetime
start = datetime.datetime.strptime("21-06-2020", "%d-%m-%Y")
end = datetime.datetime.strptime("05-07-2020", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]
for date in date_generated:
print(date.strftime("%d-%m-%Y"))
十一、巴黎时间更改为纽约时间
import pendulum
in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
print(in_paris)
in_us = in_paris.in_timezone('America/New_York')
print(in_us)
十二、使用 Python 获得最后7个工作日
from datetime import date
from datetime import timedelta
today = date.today()
for i in range(7):
d = today - timedelta(days=i)
if d.weekday() < 5:
print(d)
十三、从今天的日期和一个人的生日推算年龄
from datetime import date
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError:
birthday = born.replace(year=today.year, month=born.month + 1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
print(calculate_age(date(2001, 3, 1)))
十四、获得本月的第一个星期二
import calendar
from datetime import datetime
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
try:
tues = [day for week in monthcal for day in week if
day.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]
print(tues)
except IndexError:
print('No date found')
十五、将整数转换为日期对象
from datetime import datetime
i = 1545730073
timestamp = datetime.fromtimestamp(i)
print(timestamp)
print(type(timestamp))
十六、当前日期减去 N 天的天数
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=5)
print(d)
十七、比较两个日期
import datetime
a = datetime.datetime(2020, 12, 31, 23, 59, 59)
b = datetime.datetime(2020, 11, 30, 23, 59, 59)
print(a < b)
print(a > b)
十八、从 datetime 对象中提取年份
import datetime
year = datetime.date.today().year
print(year)
十九、根据日期找到星期几
import pendulum
dt = pendulum.parse('2021-05-18')
print(dt.day_of_week)
dt = pendulum.parse('2021-05-01')
print(dt.day_of_week)
dt = pendulum.parse('2021-05-21')
print(dt.day_of_week)
二十、从当前日期获取 7 天前的日期
from datetime import datetime, timedelta
now = datetime.now()
for x in range(7):
d = now - timedelta(days=x)
print(d.strftime("%Y-%m-%d"))
二十一、将两个日期时间对象之间的差值转换为秒
import datetime
time1 = datetime.datetime.strptime('19 01 2021', '%d %m %Y')
time2 = datetime.datetime.strptime('25 01 2021', '%d %m %Y')
difference = time2 - time1
print(difference)
seconds = difference.total_seconds()
print(seconds)
二十二、获得任何一个月的第N个星期五
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2021
month = 5
n = 2
monthcal = c.monthdatescalendar(year, month)
try:
third_friday = [
day for week in monthcal
for day in week if
day.weekday() == calendar.FRIDAY and day.month == month
][n]
print(third_friday)
except IndexError:
print('No date found')
二十三、根据周数获取日期
import datetime
from dateutil.relativedelta import relativedelta
week = 25
year = 2021
date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
print(date)
二十四、获取特定日期的工作日
import datetime
print(datetime.date(2020, 5, 15).isocalendar()[2])
二十五、创建一个 15 分钟前的 DateTime
import datetime
dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
print(dt)
二十六、从特定日期获取周的开始和结束日期
import pendulum
dt = pendulum.datetime(2012, 9, 5)
start = dt.start_of('week')
print(start.to_datetime_string())
end = dt.end_of('week')
print(end.to_datetime_string())
二十七、两个日期之间的差异(以秒为单位)
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2020-01-01 17:31:22', fmt)
d2 = datetime.strptime('2020-01-03 17:31:22', fmt)
days_diff = d2 - d1
print(days_diff.days * 24 * 60 * 60)
二十八、以这种格式获取昨天的日期MMDDYY
from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
print(yesterday.strftime('%m%d%y'))
二十九、根据今天的日期获取上周三的日期
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 2) % 7
wednesday = today - timedelta(days=offset)
print(wednesday)
三十、所有可用时区的列表打印
import pytz
for i in pytz.all_timezones:
print(i)