Home Backend Development Python Tutorial Introduction to data type time in Python (with code)

Introduction to data type time in Python (with code)

Mar 01, 2019 am 11:24 AM
python

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月的日历
Copy after login

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 type

from 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 &#39;datetime.datetime&#39;>

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 &#39;str&#39;>
# 字符串转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 &#39;datetime.datetime&#39;>

# 计算时间戳
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 &#39;datetime.datetime&#39;>
Copy after login

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
Copy after login

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 &#39;datetime.time&#39;>
Copy after login

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 &#39;datetime.timedelta&#39;>

# 可以初始化时间间隔
delta_days = timedelta(days=7)
print(delta_days, type(delta_days))  #输出:7 days, 0:00:00 <class &#39;datetime.timedelta&#39;>

# 可以通过时间间隔得到将来的时间 
future_datetime = now + delta_days
print(future_datetime)    #输出:2019-02-05 14:43:54.582315
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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 and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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 vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

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.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

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.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

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".

See all articles