search
HomeBackend DevelopmentPython TutorialIntroduction 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 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>

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>
# 字符串转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>

# 计算时间戳
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></class></class></class></class>

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></class>

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>

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

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

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment