Introduction to data type time in Python (with code)
This article brings you an introduction to data type time in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is the time data type?
The data structure representing the time type in Python is the time data type;
2.time Module
import time # 获取当前时间的时间戳 print(time.time()) #输出:1548742426.1698806 # 返回当前时间的元组 t = time.localtime() print(t) #输出:time.struct_time(tm_year=2019, tm_mon=1, tm_mday=29, tm_hour=14, tm_min=14, tm_sec=17, tm_wday=1, tm_yday=29, tm_isdst=0) # 将当前时间元组转变为字符串 print(time.asctime(time.localtime())) #输出:Tue Jan 29 14:15:51 2019 # # 格式化字符串 print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) #输出:2019-01-29 14:16:08 # # 将字符串转为时间元组 print(time.strptime('2018-11-27 08:08:08', '%Y-%m-%d %H:%M:%S')) #输出:time.struct_time(tm_year=2018, tm_mon=11, tm_mday=27, tm_hour=8, tm_min=8, tm_sec=8, tm_wday=1, tm_yday=331, tm_isdst=-1) # sleep方法, 会占用cpu时间片 print(time.sleep(5)) #5秒后输出:None # 打印日历 import calendar print(calendar.month(2019, 1)) #输出:2019年1月的日历
Timestamp: It is the number of seconds from 0:00:00 on January 1, 1970 in the 0 time zone to the given date and time (floating point type ; , the next three digits are microseconds, usually milliseconds are enough;
localtime method: Returns a tuple of the current time (including year, month, day, hour, minute, second, etc.);
asctime method: Convert the current time tuple into a string (time format in European and American countries);
strftime method: Format string;
strptime method: Contrary to the strftime method, it is used to convert a string into a time tuple;
sleep method: It will occupy cpu time slice (that is, let the entire thread pause for some time);
Print calendar: import the calendar module, and then call the month method;
3.datetime module
The datetime module in python provides the function of operating date and time. The five core objects provided by this module are: datetime (time date type), date (date type), time (time type) ), tzinfo (time zone type), timedelta (time difference type);
(1) datetime typefrom datetime import datetime # 1: 构建一个指定日期和时间的datetime对象 today = datetime(year=2019,month=1,day=29,hour=14,minute=22,second=54) print(today) #输出:2019-01-29 14:22:54 #获取当前日期时间,输出类型为datetime now = datetime.now() print(now,type(now)) #输出:2019-01-29 14:23:35.408583 <class 'datetime.datetime'> d_now = datetime.now() # datetime类型转字符串 d_str = d_now.strftime('%Y-%m-%d %H:%M:%S') print(d_str,type(d_str)) #输出:2019-01-29 14:26:12 <class 'str'> # 字符串转datetime类型 d_type = datetime.strptime(d_str,'%Y-%m-%d %H:%M:%S') print(d_type,type(d_type)) #输出:2019-01-29 14:26:12 <class 'datetime.datetime'> # 计算时间戳 timestamp = d_type.timestamp() print(timestamp) #输出:1548743501.0 # 计算时间戳 timestamp = d_type.timestamp() print(timestamp) #输出:1548743935.0 # 通过时间戳获取datetime对象 d_type = datetime.fromtimestamp(1543408827) print(d_type, type(d_type)) #输出:2018-11-28 20:40:27 <class 'datetime.datetime'>
Used to convert datetime type to string strftime method, use strptime method to convert string to datetime type;
timestamp method: calculate timestamp;
fromtimestamp method: obtain by timestamp datetime object;
- (2) date type
from datetime import date data_today = date(year=2018, month=11, day=29) print(data_today) #输出:2018-11-29
Import the date module and instantiate the date;
- (3) time type
from datetime import time now_time = time(hour=8, minute=30, second=10) print(now_time, type(now_time)) #输出:20:30:10 <class 'datetime.time'>
Import time type and instantiate time;
- (4) timedelta type
from datetime import datetime, timedelta # 时间间隔可以通过相减得到 now = datetime.now() before_datatime = datetime(year=2018, month=11, day=20, hour=8, minute=20, second=20) delta = now - before_datatime print(delta, type(delta)) #输出:70 days, 6:22:37.340041 <class 'datetime.timedelta'> # 可以初始化时间间隔 delta_days = timedelta(days=7) print(delta_days, type(delta_days)) #输出:7 days, 0:00:00 <class 'datetime.timedelta'> # 可以通过时间间隔得到将来的时间 future_datetime = now + delta_days print(future_datetime) #输出:2019-02-05 14:43:54.582315
The timedelta object represents a time period. The timedelta object can be obtained by manual instantiation or subtraction;
- (5)tzinfo type
from datetime import datetime import pytz utc_tz = pytz.timezone('UTC') print(pytz.country_timezones('cn')) # 显示中国时区的城市 #输出:['Asia/Shanghai', 'Asia/Urumqi'] print(pytz.country_timezones('us')) # 显示美国时区的城市 # #输出:['America/New_York', 'America/Detroit', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Indiana/Indianapolis', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Vevay', 'America/Chicago', 'America/Indiana/Tell_City', 'America/Indiana/Knox', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/North_Dakota/Beulah', 'America/Denver', 'America/Boise', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Sitka', 'America/Metlakatla', 'America/Yakutat', 'America/Nome', 'America/Adak', 'Pacific/Honolulu'] # # 获取时区 china_tz = pytz.timezone('Asia/Shanghai') america_tz = pytz.timezone('America/New_York') # # 获取城市本地时间 china_local_time = datetime.now(china_tz) # 东八区 america_local_time = datetime.now(america_tz) # 西五区 print(china_local_time) #输出:2019-01-29 14:51:51.252579+08:00 print(america_local_time) #输出:2019-01-29 14:51:51.252579+08:00
Install the pytz package: Enter the project and execute the pip install pytz command;
Get the time zone: pytz.timezone (region name);
-
Get the city local time: datetime.now (time zone name);
The above is the detailed content of Introduction to data type time in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
