亲宝软件园·资讯

展开

Python获取时间

lxw-pro 人气:0

获得当前时间时间戳

# 注意时区的设置
import time

# 获得当前时间时间戳
now = int(time.time())

# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArr = time.localtime(now)
other_StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArr)
print(other_StyleTime)

获取当前时间

import datetime

# 获得当前时间
now = datetime.datetime.now()

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

获取昨天日期

import datetime


def getYesterday():
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today - oneday
    return yesterday


print("昨天的日期:", getYesterday())

生成日历

# 引入日历模块
import calendar

# 输入指定年月
yy = int(input("输入年份:"))
mm = int(input("输入月份:"))

# 显示指定年月
print(calendar.month(yy, mm))

运行效果如下:

计算每个月天数

import calendar

​​​​​​​monthRange = calendar.monthrange(2022, 4)
print(monthRange)

计算3天前并转换为指定格式

import time
import datetime

# 先获得时间数组格式的日期
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=3))
# 转换为时间戳
timeStamp = int(time.mktime(threeDayAgo.timetuple()))

# 转换为其他字符串格式
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

获取时间戳的旧时间

import time
import datetime

# 给定时间戳
timeStamp1 = 1643892140
dateArray = datetime.datetime.utcfromtimestamp(timeStamp1)

threeDayAgo = dateArray - datetime.timedelta(days=3)
print(threeDayAgo)

获取时间并指定格式

import time

timeStamp = 1825135462
timeArr = time.localtime(timeStamp)
other_StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArr)
print(other_StyleTime)

import datetime

timeStamp = 2022020321
dateArr = datetime.datetime.utcfromtimestamp(timeStamp)
other_StyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(other_StyleTime)

pandas 每日一练

print()只为换行用,方便看运行结果

# -*- coding = utf-8 -*-
# @Time : 2022/7/22 19:46
# @Author : lxw_pro
# @File : pandas-5 练习.py
# @Software : PyCharm

import pandas as pd

21读取本地EXCEL数据

df = pd.read_excel('test-5.xlsx')
print("EXCEL数据如下:\n", df)

print()

22查看df数据前5行

print("df数据前5行为:\n", df.head())

print()

23将popularity列数据转换为最大值与最小值的平均值

import re
def func(df):
    zfg = df['popularity'].split('-')
    smin = int(zfg[0].strip('f'))
    smax = int(zfg[1].strip('f'))
    df['popularity'] = int((smin+smax)/2)
    return df


df = df.apply(func, axis=1)
print(df)

print()

24将数据根据project进行分组并计算平均分

fzj = df.groupby('project').mean()
print("分组后的平均分为:\n", fzj)

print()

25将test_time列具体时间拆分为两部分(一半日期,一半时间)

df['date'] = df['test_time'].dt.date
df['time'] = df['test_time'].dt.time

print(df.head())

df.to_excel('text5.xlsx')	# 也可将所运行的结果导入另一个新的EXCEL

相关程序运行结果如下:

21-22:

23-24:

 

25:

存入的新EXCEL数据:

加载全部内容

相关教程
猜你喜欢
用户评论