[python get time]

Several formats for getting time

Personal nickname: [lxw-pro]
Personal homepage: Welcome to [my]
homepage Personal insight: “Failure is the mother of success”, this is the same truth, only by summing up in failure and growing in failure can you become a generation master in the IT industry.

Get current time timestamp

# Note the time zone settings 
import time

# Get the current time timestamp 
now = int (time.time())

# Convert to other date formats, such as: "%Y-%m-%d %H:%M:%S"
timeArr = time.localtime(now)
other_StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArr)

get current time

import datetime

# get current time
now = datetime.datetime.now()

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

get yesterday’s date

import datetime

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

print( "Yesterday's date:" , getYesterday())

Generate calendar

# import calendar module
import calendar

# Enter the specified year and month 
yy = int(input( "Enter the year:" ))
mm = int(input( "Enter month:" ))

# Display the specified year and month 
print(calendar.month(yy, mm))

The operation effect is as follows:

Calculate the number of days per month

import calendar

monthRange = calendar.monthrange(2022, 4)

Calculate 3 days ago and convert to specified format

import time
import datetime

# First get the date in time array format 
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days= 3 ))
 # Convert to timestamp 
timeStamp = int (time.mktime(threeDayAgo.timetuple()))

# Convert to other string format 
otherStyleTime = threeDayAgo.strftime( "%Y-%m-%d %H:%M:%S" )
 print (otherStyleTime)

Get the old time of the timestamp

import time
import datetime

# given timestamp
timeStamp1 = 1643892140
dateArray = datetime.datetime.utcfromtimestamp(timeStamp1)

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

Get time and specify format

import time

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


import datetime

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


Pandas daily practice:

# -*- coding = utf-8 -*-
# @Time : 2022/7/22 19:46
# @Author : lxw_pro
# @Software : PyCharm

import pandas as pd

21. Read local EXCEL data

df = pd.read_excel( 'test-5.xlsx' )
 print ( "EXCEL data is as follows:\n" , df)


22. View the first 5 rows of df data

print ( "The first 5 lines of df data: \n" , df.head())


23. Convert the popularity column data to the average of the maximum and minimum values

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)


24. Group the data according to the project and calculate the average score

fzj = df.groupby( 'project' ).mean()
 print ( "The average score after grouping:\n" , fzj)


25. Split the specific time of the test_time column into two parts (half date, half time)

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


df.to_excel( 'text5.xlsx' )  # You can also import the results of the run into another new EXCEL

The results of running the relevant programs are as follows:


Word of the day:

The most wonderful discovery among friends is to grow up on different paths, but it does not breed estrangement!

Continuing to update…

Welcome to followWeChat public account[ Program Life 6 ], let’s discuss and learn together! ! !

Leave a Comment

Your email address will not be published. Required fields are marked *