专业编程基础技术教程

网站首页 > 基础教程 正文

python中的今天、昨天、此刻与凌晨

ccvgpt 2024-08-12 15:01:59 基础教程 12 ℃

python 小白,今天写脚本遇到获取当前时间,昨天0点到23:59:59的问题,于是上网搜了一番,结果发现很简单的问题大家写的都是千奇百怪,有的甚至晦涩难懂,所以自己便花了一点时间专门整理后记录如下,希望给大家参考

下面分别是利用datetime和time 模块打印时间并进行格式化

python中的今天、昨天、此刻与凌晨

## datetime

# 表示当天(今天)日期

import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
print(today)
print(yesterday)




# 表示当前时间

now = datetime.datetime.now()
print(now)
now = now.strftime("%Y-%m-%d %H:%M:%S")
print(now)



# 昨天此刻

now = datetime.datetime.now()
yes_time = now + datetime.timedelta(days=-1)
print(yes_time)
yes_time = yes_time.strftime("%Y-%m-%d %H:%M:%S")
print(yes_time)


# 获取今天零点(当天0点时间)

now = datetime.datetime.now()
#方式1:
today_zero = now.strftime('%Y-%m-%d 00:00:00')
print(today_zero)
#方式2:
today_zero = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,microseconds=now.microsecond)
print(today_zero)



# 获取当天23:59:59

# 方式1:
today_last = now.strftime('%Y-%m-%d 23:59:59')
print(today_last)
# 方式2:
today_last = today_zero + datetime.timedelta(hours=23, minutes=59, seconds=59)
print(today_last)
?

?# 获取昨天0点

# 方式1:
yes_time = now + datetime.timedelta(days=-1)
yesterday_zero = yes_time.strftime('%Y-%m-%d 00:00:00')
print(yesterday_zero)
# 方式2: 
yesterday_zero = now - datetime.timedelta(days=1, hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond)
print(yesterday_zero)

# 获取昨天23:59

# 方式1: 
yesterday_end = yes_time.strftime('%Y-%m-%d 23:59:59')
print(yesterday_end)
# 方式2: 
yesterday_end = yesterday_zero + datetime.timedelta(hours=23, minutes=59, seconds=59)
print(yesterday_end)



## time

import time
# 打印当前时间戳
time_stamp=time.time()
print(time_stamp)
# 打印当前时间的时间元组(本地时间)
now_tuple = time.localtime(time.time())
print(now_tuple)
# 打印当前时间的格式化时间
now_form = time.strftime('%Y-%m-%d %H:%M:%S', now_tuple)
print(now_form)
# 打印当天0点的格式化时间
zero_form = time.strftime('%Y-%m-%d 00:00:00', now_tuple)
print(zero_form)
# 将当天0点的格式化时间转化为时间元组
zero_tuple = time.strptime(zero_form, '%Y-%m-%d %H:%M:%S')
print(zero_tuple)
# 将当天0点的时间元组转化为时间戳
time_now = time.mktime(zero_tuple)
print(time_now)

Tags:

最近发表
标签列表