您现在的位置是:网站首页 > 博客日记 >

python日期时间案例(持续更新)

作者:YXN-python 阅读量:66 发布日期:2023-03-25

当前相关

1、展示当前日期和时间

import time
from time import gmtime, strftime

t = time.localtime()
print(time.asctime(t))  # Mon Mar 25 13:17:04 2024
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))  # Mon, 25 Mar 2024 05:17:04 +0000
print(strftime("%A", gmtime()))  # Monday
print(strftime("%D", gmtime()))  # 03/25/24
print(strftime("%B", gmtime()))  # March
print(strftime("%y", gmtime()))  # 24

# 将秒转换为GMT日期
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))  # Fri, 13 Feb 2009 23:31:30 +0000

2、以毫秒为单位获取当前时间

import time

milliseconds = int(round(time.time() * 1000))
print(milliseconds)  # 1711344420374

3、以 MST、EST、UTC、GMT 和 HST 获取当前日期时间

from datetime import datetime
from pytz import timezone

mst = timezone('MST')
print("MST:", datetime.now(mst))  # MST: 2024-03-24 22:29:18.306016-07:00

est = timezone('EST')
print("EST:", datetime.now(est))  # EST: 2024-03-25 00:29:18.306016-05:00

utc = timezone('UTC')
print("UTC:", datetime.now(utc))  # UTC: 2024-03-25 05:29:18.306016+00:00

gmt = timezone('GMT')
print("GMT:", datetime.now(gmt))  # GMT: 2024-03-25 05:29:18.307015+00:00

hst = timezone('HST')
print("HST:", datetime.now(hst))  # HST: 2024-03-24 19:29:18.307015-10:00

 

转换相关

1、将天、小时、分钟转换为秒

SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400

days = int(input("输入天数: "))
hours = int(input("输入小时数: "))
minutes = int(input("输入分钟数: "))
seconds = int(input("输入秒数: "))

# 计算天、小时、分钟和秒
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("总秒数: ", "%d" % (total_seconds))

2、将字符串转换为日期时间对象

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)  # 2015-01-07 13:15:00

# 如果您不知道日期格式
date2 = parser.parse(d2)
print(type(date2))
print(date2)  # 2015-01-07 13:33:00

3、将整数转换为日期对象

from datetime import datetime

i = 1545730073
timestamp = datetime.fromtimestamp(i)

print(timestamp)  # 2018-12-25 17:27:53

 

计算相关

1、计算两个日期时间对象之间的时差

import datetime

datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
date1 = '2024-04-16 10:01:28.585'
date2 = '2024-03-10 09:56:28.067'
diff = datetime.datetime.strptime(date1, datetimeFormat) \
       - datetime.datetime.strptime(date2, datetimeFormat)

print("Difference:", diff)  # Difference: 37 days, 0:05:00.518000
print("Days:", diff.days)  # Days: 37
print("Microseconds:", diff.microseconds)  # Microseconds: 518000
print("Seconds:", diff.seconds)  # Seconds: 300

2、将 5 分钟添加到 Unix 时间戳

import datetime
import calendar

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple()))  # 1711345184

3、在 Python 中遍历一系列日期

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"))  # 21-06-2020 22-06-2020 23-06-2020 ...

4、使用 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)  # 2024-03-25 2024-03-22 2024-03-21 ...

5、从今天的日期和一个人的生日推算年龄

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)))  # 23

6、从给定的日期当中获取星期几

import datetime

dayofweek = datetime.date(2010, 6, 16).strftime("%A")
print(dayofweek)  # Wednesday
# weekday 星期一是0,星期日是6
print("weekday():", datetime.date(2010, 6, 16).weekday())  # weekday(): 2

# isoweekday() 周一是1,周日是7
print("isoweekday()", datetime.date(2010, 6, 16).isoweekday())  # isoweekday() 3

dayofweek = datetime.datetime.today().strftime("%A")
print(dayofweek)  # Monday
print("weekday():", datetime.datetime.today().weekday())  # weekday(): 0
print("isoweekday()", datetime.datetime.today().isoweekday())  # isoweekday() 1

7、当前日期减去 N 天的天数

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=5)
print(d)  # 2024-03-20 13:43:18.601164

8、比较两个日期

import datetime

a = datetime.datetime(2020, 12, 31, 23, 59, 59)
b = datetime.datetime(2020, 11, 30, 23, 59, 59)

print(a < b)  # False
print(a > b)  # True

9、从当前日期获取 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"))  # 2024-03-25 2024-03-24 2024-03-23 ...

10、将两个日期时间对象之间的差值转换为秒

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)  # 6 days, 0:00:00

seconds = difference.total_seconds()
print(seconds)  # 518400.0

11、从 Python 中的周数获取日期

import datetime
from dateutil.relativedelta import relativedelta

week = 25
year = 2021
date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
print(date)  # 2021-06-25

12、创建一个 15 分钟前的 DateTime

import datetime

dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
print(dt)  # 2024-03-25 13:35:27.495024

13、计算时间减去指定时间后的时间

def time_diff(times, seconds):
    """
    计算两个时间差
    :param times: 时间字符串 如:00:15:14.96 或 00:15:14
    :param seconds: 秒数
    :return: 如:00:15:09.96
    """
    from datetime import datetime, timedelta
    if '.' in times:
        format_ = "%H:%M:%S.%f"
    else:
        format_ = "%H:%M:%S"
    time_obj = datetime.strptime(times, format_)
    new_time_obj = time_obj - timedelta(seconds=seconds)

    return new_time_obj.time()

 

 

YXN-python

2023-03-25