current position：Home>Run through Python date and time processing (Part 2)
Run through Python date and time processing (Part 2)
2022-01-31 11:26:01 【Lei Xuewei】
「 This is my participation 11 The fourth of the yuegengwen challenge 9 God , Check out the activity details ：2021 One last more challenge 」
ceremonial Python Column No 33 piece , Classmate, stop , Don't miss this from 0 The beginning of the article ！
In the previous article, we learned a little Python The acquisition of time , This time continue to learn the time zone conversion of dates , Format and so on .
- Time zone conversion display
- Date formatting
- Number of seconds And date And String conversion
We often use , For example, global business shows different times according to different customers （ Format, etc. ）
stay python The following two modules cover common date processing
import time import calender Copy code
Let's look at these two modules .
Type conversion in time processing :struct_time vs str
Python Create a time in , Specifically, create a struct_time Need one 9 Tuples of elements to construct .
asctime The function helps us format this type of time as a string .
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/11/10 22:49 In the morning # @Author : LeiXueWei # @CSDN/Juejin/Wechat: Lei Xuewei # @XueWeiTag: CodingDemo # @File : createtime.py # @Project : hello import time # fixed time: time.struct_time(tm_year=2021, tm_mon=11, tm_mday=10, tm_hour=22, tm_min=55, tm_sec=11, tm_wday=16, tm_yday=16, tm_isdst=16) the9fields = (2021, 11, 10, 22, 55, 11, 16, 16, 16) fixed = time.struct_time(the9fields) print("fixed time:", fixed) print("type:", type(fixed)) result = time.asctime(the9fields) # similar struct_time, need 9 Tuple parameters composed of elements . print("asc time:", result) print("type:", type(result)) localtime = time.localtime() print("local time:", localtime) print("type:", type(localtime)) print("asc time:", time.asctime(localtime)) Copy code
The operation effect is as follows ：
This ticks It's from 0 Calculate all the time , Cumulative seconds to date .
You can run this program every second , Every time ticks Value plus 1（ The approximate ）
Specify the input to construct the time ：
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/11/10 22:49 In the morning # @Author : LeiXueWei # @CSDN/Juejin/Wechat: Lei Xuewei # @XueWeiTag: CodingDemo # @File : createtime.py # @Project : hello import time #fixed time: time.struct_time(tm_year=2021, tm_mon=11, tm_mday=10, tm_hour=22, tm_min=55, tm_sec=11, tm_wday=16, tm_yday=16, tm_isdst=16) fixed = time.struct_time((2021, 11, 10, 22, 55, 11, 16, 16, 16)) print("fixed time:", fixed) Copy code
The operation effect is as follows ：
Time and string conversion
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/11/10 22:49 In the morning # @Author : LeiXueWei # @CSDN/Juejin/Wechat: Lei Xuewei # @XueWeiTag: CodingDemo # @File : createtime2.py # @Project : hello import time sec = 3600 # An hour after the beginning of the era （GMT 19700101 In the morning ） # gmtime = time.gmtime(sec) print("gmtime:", gmtime) # GMT print("type:", type(gmtime)) print(time.strftime("%b %d %Y %H:%M:%S", gmtime)) print(time.strftime("%Y-%m-%d %H:%M:%S %Z", gmtime)) # Print date plus time zone print("*" * 16) localtime = time.localtime(sec) print("localtime:", localtime) # Local time print("type:", type(localtime)) print(time.strftime("%b %d %Y %H:%M:%S", localtime)) print(time.strftime("%Y-%m-%d %H:%M:%S %Z", localtime)) # Print date plus time zone # Try another format print(time.strftime("%D", localtime)) print(time.strftime("%T", localtime)) Copy code
Here are the results ：
For time formatting functions （strftime） It doesn't care about the time you pass in （struct_time) What time zone is it , Still output to you , It's also true .
But when we write programs to get data , The time zone information must be returned to the client as it is , Or is it UI End , Finally, the display is adjusted by the local time zone setting of the client .
Python Date processing is still quite sufficient , Practice more .
by the way , like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column
Continuous learning and continuous development , I'm Lei Xuewei ！
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !
author[Lei Xuewei],Please bring the original link to reprint, thank you.
The sidebar is recommended
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes ｜ 538 ｜ 1038 (Java / C / C + + / Python / go / trust)
guess what you like
How IOS developers learn python programming 3-operator 2
How IOS developers learn python programming 2-operator 1
[Python applet] 8 lines of code to realize file de duplication
Python uses the pynvml tool to obtain the working status of GPU
Data mining: Python actual combat multi factor analysis
Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
Use Python VTK to batch read 2D slices and display 3D models
Complete image cutting using Python version VTK
Python interface automation test framework (basic) -- common data types Dict
Django (make an epidemic data report)
- Python specific text extraction in actual combat challenges the first step of efficient office
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert（python）
- leetcode 2062. Count Vowel Substrings of a String（python）
- Analysis of Matplotlib module of Python visualization
- Django permission management
- Python integrated programming -- visual hot search list and new epidemic situation map
- [Python data collection] scripy realizes picture download
- Python interface automation test framework (basic part) -- loop statement of process control for & while
- Daily python, Chapter 9, while loop
- Van * Python | save the crawled data with docx and PDF
- Five life saving Python tips
- Django frequency control
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence（python）
- leetcode 2027. Minimum Moves to Convert String（python）
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph（python）
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores（python）
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching