The Story That Explains Time in Python ⏰Python में समय समझाने वाली कहानी ⏰一个讲清 Python 时间的故事 ⏰
There is the stopwatch in the guard's hand: "The train was 47 seconds late." That measures a duration.
And deep inside the ticket computer there is a ticker tape: one number,
1783866600, that grows by one every second. That is how computers store a moment.All three can describe the same instant, and they keep turning into each other. The clock becomes the number when you save to a database. The number becomes the clock when you show it to a passenger. The stopwatch is the gap between two numbers. Python gives you a tool for each:
datetime for the calendar, time for the stopwatch, and Unix timestamps for the ticker tape.गार्ड के हाथ में स्टॉपवॉच है: "ट्रेन 47 सेकंड देर से आई।" यह एक अवधि नापती है।
और टिकट कंप्यूटर के अंदर एक टिकर टेप है: एक नंबर,
1783866600, जो हर सेकंड एक बढ़ता है। कंप्यूटर किसी पल को ऐसे ही रखते हैं।तीनों एक ही पल बता सकते हैं, और ये एक-दूसरे में बदलते रहते हैं। Database में save करते समय घड़ी नंबर बन जाती है। यात्री को दिखाते समय नंबर फिर घड़ी बन जाता है। स्टॉपवॉच दो नंबरों का अंतर है। Python हर एक के लिए औज़ार देता है: कैलेंडर के लिए
datetime, स्टॉपवॉच के लिए time, और टिकर टेप के लिए Unix timestamps।列车员手里有 秒表:"列车晚点了 47 秒。"它测量的是一段 时长。
而售票电脑内部有一条 计数纸带:一个数字
1783866600,每秒加一。电脑就是这样存储某一时刻的。三者可以描述同一瞬间,而且不断相互转换。存入数据库时,时钟变成数字;显示给乘客时,数字又变回时钟;秒表则是两个数字之差。Python 为每一种都提供了工具:
datetime 对应日历,time 对应秒表,Unix 时间戳 对应计数纸带。This tutorial focuses on the conversions you will do most: turning a human-readable string into a Unix timestamp, and turning that number back into any format you want. They sit behind every log parser, database write, API response and scheduled job.
यह tutorial उन बदलावों पर ध्यान देता है जो आप सबसे ज़्यादा करेंगे: इंसान के पढ़ने लायक string को Unix timestamp में बदलना, और उस नंबर को वापस किसी भी format में लाना। हर log parser, database write, API response और scheduled job के पीछे यही होता है।
本教程聚焦你最常做的转换:把 人类可读的字符串 变成 Unix 时间戳,再把这个数字变回任何你想要的格式。每个日志解析器、数据库写入、API 响应和定时任务背后都是它们。
A moment and the way you write it down are different things. "2026-07-12 14:30:00" is a string, 1783866600 is a number, and datetime(2026, 7, 12, 14, 30) is an object. They can all point to the same instant — but only if you know the time zone. The string alone does not say whether it is 14:30 in London or in Delhi, and those are 5½ hours apart.
एक पल और उसे लिखने का तरीका दो अलग चीज़ें हैं। "2026-07-12 14:30:00" एक string है, 1783866600 एक नंबर है, और datetime(2026, 7, 12, 14, 30) एक object है। ये सब एक ही पल की ओर इशारा कर सकते हैं — पर तभी जब time zone पता हो। सिर्फ़ string से पता नहीं चलता कि यह London का 14:30 है या Delhi का, और इनमें 5½ घंटे का अंतर है।
某一时刻 与它的 写法 是两回事。"2026-07-12 14:30:00" 是字符串,1783866600 是数字,datetime(2026, 7, 12, 14, 30) 是对象。它们都可以指向同一瞬间 — 但前提是你知道时区。单看字符串,无法知道这是伦敦的 14:30 还是德里的 14:30,而两者相差 5.5 小时。
Look for the interactive boxes: the Epoch Explorer (Section 03), the strftime Builder and strptime Matcher (06), the Time Zone Clock (10) and the timedelta Calculator (11). Their results were checked against real Python 3.13.
Interactive डिब्बे खोजें: Epoch Explorer (Section 03), strftime Builder और strptime Matcher (06), Time Zone Clock (10) और timedelta Calculator (11)। इनके नतीजे असली Python 3.13 से जाँचे गए हैं।
请留意这些互动框:纪元探索器(第 03 节)、strftime 构建器 和 strptime 匹配器(06)、时区时钟(10)和 timedelta 计算器(11)。它们的结果都与真实的 Python 3.13 核对过。
Python's Three Time Modules 🧰Python के तीन Time Modules 🧰Python 的三个时间模块 🧰
timedelta and timezone. Compare, format, and do arithmetic like "30 days from now". You will use it most of the time.timedelta और timezone। तुलना, format, और "आज से 30 दिन बाद" जैसी गणना। ज़्यादातर समय यही इस्तेमाल होगा।timedelta 和 timezone。比较、格式化,以及"30 天后"这样的运算。你大部分时间都会用它。time.time() gives the current timestamp, time.sleep() pauses, time.perf_counter() measures how long code takes.time.time() मौजूदा timestamp देता है, time.sleep() रोकता है, time.perf_counter() नापता है कि code कितनी देर चला।time.time() 返回当前时间戳,time.sleep() 暂停,time.perf_counter() 测量代码耗时。calendar.isleap(2028), monthrange(2026, 2), text calendars. Handy now and then.calendar.isleap(2028), monthrange(2026, 2), text कैलेंडर। कभी-कभी काम आता है।calendar.isleap(2028)、monthrange(2026, 2)、文本日历。偶尔很有用。ZoneInfo("Asia/Kolkata"), with daylight saving rules. On Windows, run pip install tzdata once.ZoneInfo("Asia/Kolkata"), daylight saving नियमों के साथ। Windows पर एक बार pip install tzdata चलाएँ।ZoneInfo("Asia/Kolkata"),含夏令时规则。在 Windows 上请先运行一次 pip install tzdata。Here is "what time is it right now?" from four angles. This example uses the real clock, so your output will show your own date and time.
"अभी कितने बजे हैं?" चार नज़रियों से। यह उदाहरण असली घड़ी इस्तेमाल करता है, इसलिए आपके output में आपकी अपनी तारीख़ और समय होगा।
从四个角度回答"现在几点?"。这个例子使用真实时钟,所以你的输出会显示你自己的日期和时间。
from datetime import datetime
import time
now = datetime.now() # the real clock - your output will differ
print(now) # a datetime object
print(time.time()) # a Unix timestamp (seconds since 1970)
print(now.isoformat()) # an ISO 8601 string
print(now.strftime("%A, %d %B %Y")) # a string in your own layout
The Unix Epoch — Counting Seconds Since 1970 🔢Unix Epoch — 1970 से सेकंड गिनना 🔢Unix 纪元 — 从 1970 年开始数秒 🔢
A Unix timestamp (or epoch time) is the number of seconds since a fixed starting point: 1 January 1970, 00:00:00 UTC. That point is called the epoch. Unix was being built around then, and one plain number was the simplest way to store time: no time zones, no month names, easy to compare and sort. Databases, log files, APIs and file systems still use it.
Unix timestamp (या epoch time) एक तय शुरुआती बिंदु से बीते सेकंडों की संख्या है: 1 जनवरी 1970, 00:00:00 UTC। उस बिंदु को epoch कहते हैं। Unix उसी समय बन रहा था, और समय रखने का सबसे आसान तरीका एक सादा नंबर था: कोई time zone नहीं, कोई महीने का नाम नहीं, तुलना और sort करना आसान। Databases, log files, APIs और file systems आज भी इसे इस्तेमाल करते हैं।
Unix 时间戳(或 纪元时间)是从一个固定起点开始经过的秒数:1970 年 1 月 1 日 00:00:00 UTC。这个起点叫作 纪元(epoch)。Unix 正是那时诞生的,用一个普通数字存储时间最简单:没有时区,没有月份名称,易于比较和排序。数据库、日志文件、API 和文件系统至今仍在使用它。
Every timestamp counts seconds from the red dot. Dates under each dot are UTC.
हर timestamp लाल बिंदु से सेकंड गिनता है। हर बिंदु के नीचे की तारीख़ UTC में है।
每个时间戳都从红点开始计秒。各点下的日期均为 UTC。
Try It — Epoch Explorerकरके देखें — Epoch Explorer动手试试 — 纪元探索器
Drag the slider or pick a landmark. You see the same number as a UTC time, as Indian time (UTC+5:30), and as the 32 bits an old system would store. Press Play to watch the ticker tape run, then speed it up. Jump to Y2038 max, play at real speed, and watch the red sign bit flip.
Slider खींचें या कोई landmark चुनें। आप वही नंबर UTC समय, भारतीय समय (UTC+5:30), और उन 32 bits के रूप में देखेंगे जो पुराना system रखता। टिकर टेप चलते देखने के लिए Play दबाएँ, फिर रफ़्तार बढ़ाएँ। Y2038 max पर जाएँ, असली रफ़्तार से चलाएँ, और लाल sign bit पलटते देखें।
拖动滑块或选择一个里程碑。你会看到同一个数字作为 UTC 时间、印度时间(UTC+5:30)以及老系统会存储的 32 位二进制。按 播放 看计数纸带走动,再调快速度。跳到 Y2038 max,以真实速度播放,看红色符号位翻转。
Old C programs stored timestamps in a signed 32-bit integer. Its largest value, 2,147,483,647, is reached at 2038-01-19 03:14:07 UTC. One second later the number wraps around to −2,147,483,648, which means 13 December 1901. Python integers have no size limit, and modern systems use 64 bits. But embedded devices, old databases and file formats can still break — so do not store timestamps in 32-bit columns.
पुराने C programs timestamps को signed 32-bit integer में रखते थे। इसकी सबसे बड़ी value, 2,147,483,647, 2038-01-19 03:14:07 UTC पर पहुँचती है। एक सेकंड बाद नंबर घूमकर −2,147,483,648 बन जाता है, यानी 13 दिसंबर 1901। Python integers की कोई सीमा नहीं, और आधुनिक systems 64 bits इस्तेमाल करते हैं। पर embedded devices, पुराने databases और file formats अब भी टूट सकते हैं — इसलिए timestamps को 32-bit columns में न रखें।
老的 C 程序把时间戳存在 有符号 32 位整数 里。它的最大值 2,147,483,647 会在 2038-01-19 03:14:07 UTC 到达。再过一秒,数字回绕成 −2,147,483,648,也就是 1901 年 12 月 13 日。Python 整数没有大小限制,现代系统也使用 64 位。但嵌入式设备、老数据库和文件格式仍可能出错 — 所以不要把时间戳存进 32 位的列。
Unix time pretends every day has exactly 86,400 seconds. The real Earth day sometimes gets a leap second; Unix time simply ignores it. That is why you can turn any timestamp into a date with plain division — and why timestamps are not perfect for science-grade timing.
Unix time मानता है कि हर दिन में ठीक 86,400 सेकंड होते हैं। असली पृथ्वी के दिन में कभी-कभी एक leap second जुड़ता है; Unix time उसे बस नज़रअंदाज़ करता है। इसीलिए किसी भी timestamp को सादे भाग से तारीख़ में बदला जा सकता है — और इसीलिए timestamps वैज्ञानिक स्तर के समय के लिए सटीक नहीं हैं।
Unix 时间假定每天恰好 86,400 秒。真实的地球日有时会加入一个 闰秒;Unix 时间直接忽略它。所以任何时间戳都能用简单除法换算成日期 — 这也是时间戳不适合科学级计时的原因。
The Conversion Triangle 🔺बदलाव का त्रिकोण 🔺转换三角 🔺
Remember this picture. A moment can be a string, a datetime object or a timestamp, and each arrow has a named function. The datetime object sits in the middle: strings and timestamps always pass through it.
यह तस्वीर याद रखें। एक पल string, datetime object या timestamp हो सकता है, और हर तीर का एक नाम वाला function है। Datetime object बीच में है: strings और timestamps हमेशा इसी से होकर गुज़रते हैं।
记住这张图。一个时刻可以是 字符串、datetime 对象 或 时间戳,每个箭头都有对应的函数。datetime 对象位于中间:字符串和时间戳总要经过它。
Learn the four solid arrows; every other conversion is two of them in a row.
चार ठोस तीर सीख लें; बाक़ी हर बदलाव इनमें से दो का क्रम है।
学会四个实线箭头;其他任何转换都是其中两个依次相连。
datetime.strptime(text, fmt)dt.strftime(fmt)dt.timestamp()datetime.fromtimestamp(ts, tz)tz=timezone.utc to get UTC.tz=timezone.utc दें।tz=timezone.utc。Human String ↔ datetime 🔁इंसानी String ↔ datetime 🔁人类字符串 ↔ datetime 🔁
String → datetime with strptime()strptime() से String → datetime用 strptime() 把字符串变成 datetime
strptime means "string parse time". You give it the text and a format that describes exactly how the text is laid out. Python matches the two and returns a datetime.
strptime का मतलब है "string parse time"। आप इसे text और एक format देते हैं जो बताता है कि text ठीक-ठीक कैसे लिखा है। Python दोनों को मिलाता है और datetime लौटाता है।
strptime 意为 "string parse time"。你给它文本 和 一个准确描述文本布局的格式。Python 把两者对照,返回一个 datetime。
from datetime import datetime
dt = datetime.strptime("2026-07-12 14:30:00", "%Y-%m-%d %H:%M:%S")
print(dt)
print(type(dt))
dt2 = datetime.strptime("12/Jul/2026", "%d/%b/%Y")
print(dt2)
print(dt.year, dt.month, dt.day)
print(dt.weekday(), dt.strftime("%A")) # Monday is 0, so Sunday is 6
datetime → String with strftime()strftime() से datetime → String用 strftime() 把 datetime 变成字符串
strftime means "string format time". It uses the same %-codes, but goes the other way. Here we fix "now" to one moment so the output is the same every time.
strftime का मतलब है "string format time"। यह वही %-codes इस्तेमाल करता है, पर उल्टी दिशा में। यहाँ हमने "now" को एक तय पल पर रखा है ताकि output हर बार एक जैसा रहे।
strftime 意为 "string format time"。它使用同样的 % 代码,但方向相反。这里我们把"现在"固定为某一时刻,让输出每次都一样。
from datetime import datetime
now = datetime(2026, 7, 12, 14, 30, 15) # a fixed "now", so the output repeats
print(now.strftime("%Y-%m-%d")) # ISO date
print(now.strftime("%Y-%m-%d %H:%M:%S")) # ISO date and time
print(now.strftime("%d/%m/%Y")) # India / UK style
print(now.strftime("%m/%d/%Y")) # US style
print(now.strftime("%A, %d %B %Y"))
print(now.strftime("%d %b '%y"))
print(now.strftime("%I:%M %p")) # 12-hour clock
print(now.strftime("backup_%Y%m%d_%H%M%S.zip"))
strptime — parse: string in, datetime out.strftime — format: datetime in, string out.
And notice where they live: strptime is called on the class (datetime.strptime(...)), strftime on an object (dt.strftime(...)).
strptime — parse: string अंदर, datetime बाहर।strftime — format: datetime अंदर, string बाहर।
और ध्यान दें ये कहाँ रहते हैं: strptime class पर बुलाया जाता है (datetime.strptime(...)), strftime एक object पर (dt.strftime(...))।
strptime — parse:输入字符串,输出 datetime。strftime — format:输入 datetime,输出字符串。
还要注意它们的位置:strptime 在 类 上调用(datetime.strptime(...)),strftime 在 对象 上调用(dt.strftime(...))。
The Format Code Reference 📋Format Code संदर्भ 📋格式代码参考 📋
strptime and strftime share one vocabulary of %-codes. The examples below are real Python output for datetime(2026, 7, 12, 14, 30, 15, 123456, tzinfo=ZoneInfo("Asia/Kolkata")) — a Sunday.
strptime और strftime %-codes की एक ही शब्दावली बाँटते हैं। नीचे के उदाहरण datetime(2026, 7, 12, 14, 30, 15, 123456, tzinfo=ZoneInfo("Asia/Kolkata")) — एक रविवार — के लिए असली Python output हैं।
strptime 和 strftime 共用一套 % 代码。下面的示例是 datetime(2026, 7, 12, 14, 30, 15, 123456, tzinfo=ZoneInfo("Asia/Kolkata"))(星期日)的真实 Python 输出。
| CodeCode代码 | Meaningमतलब含义 | Exampleउदाहरण示例 |
|---|---|---|
%Y | 4-digit year4 अंकों का साल4 位年份 | 2026 |
%y | 2-digit year2 अंकों का साल2 位年份 | 26 |
%m | month number, 2 digitsमहीने का नंबर, 2 अंक月份数字,2 位 | 07 |
%B | month nameमहीने का नाम月份全名 | July |
%b | short month nameछोटा महीने का नाम月份缩写 | Jul |
%d | day of month, 2 digitsमहीने का दिन, 2 अंक日,2 位 | 12 |
%A | weekday nameहफ़्ते के दिन का नाम星期全名 | Sunday |
%a | short weekday nameछोटा दिन का नाम星期缩写 | Sun |
%w | weekday number, Sunday = 0दिन का नंबर, रविवार = 0星期数字,周日 = 0 | 0 |
%u | ISO weekday, Monday = 1 … Sunday = 7ISO दिन, सोमवार = 1 … रविवार = 7ISO 星期,周一 = 1 … 周日 = 7 | 7 |
%H | hour, 24-hour clockघंटा, 24-घंटे की घड़ी小时,24 小时制 | 14 |
%I | hour, 12-hour clockघंटा, 12-घंटे की घड़ी小时,12 小时制 | 02 |
%p | AM or PMAM या PMAM 或 PM | PM |
%M | minute (not month!)minute (month नहीं!)分钟(不是月份!) | 30 |
%S | secondसेकंड秒 | 15 |
%f | microseconds, 6 digitsmicroseconds, 6 अंक微秒,6 位 | 123456 |
%j | day of the yearसाल का दिन一年中的第几天 | 193 |
%U | week of year (Sunday first)साल का हफ़्ता (रविवार से)一年中的第几周(周日为首) | 28 |
%z | UTC offset (empty if naive)UTC offset (naive हो तो ख़ाली)UTC 偏移(naive 时为空) | +0530 |
%Z | time zone name (empty if naive)time zone का नाम (naive हो तो ख़ाली)时区名(naive 时为空) | IST |
%c | locale's date and timelocale की तारीख़ और समय本地化的日期时间 | Sun Jul 12 14:30:15 2026 |
%x | locale's datelocale की तारीख़本地化的日期 | 07/12/26 |
%X | locale's timelocale का समय本地化的时间 | 14:30:15 |
%% | a literal % signएक सादा % चिह्न字面 % 符号 | % |
%A, %B, %p and %c follow the computer's locale. The values above are the default English (C) locale. On a computer set to Hindi or Chinese, %B may print a Hindi or Chinese month name — and strptime("Jul", "%b") may then fail. For data files and APIs, stick to number codes like %Y-%m-%d.
%A, %B, %p और %c कंप्यूटर के locale को मानते हैं। ऊपर की values default English (C) locale की हैं। Hindi या Chinese पर set कंप्यूटर पर %B Hindi या Chinese महीने का नाम छाप सकता है — और तब strptime("Jul", "%b") fail हो सकता है। Data files और APIs के लिए %Y-%m-%d जैसे नंबर वाले codes ही रखें।
%A、%B、%p 和 %c 遵循电脑的 区域设置(locale)。上面的值是默认英文(C)locale。在设为印地语或中文的电脑上,%B 可能输出印地语或中文月份名 — 此时 strptime("Jul", "%b") 可能失败。数据文件和 API 请坚持用 %Y-%m-%d 这类数字代码。
Try It — strftime Builderकरके देखें — strftime Builder动手试试 — strftime 构建器
Type a format, or click codes to add them. Each code turns into its own coloured piece of the result. Try the presets, switch the moment and the time zone, and try the "bug" preset to see a classic mistake.
Format लिखें, या codes पर click करके जोड़ें। हर code नतीजे के अपने रंगीन हिस्से में बदलता है। Presets आज़माएँ, पल और time zone बदलें, और एक आम ग़लती देखने के लिए "bug" preset आज़माएँ।
输入一个格式,或点击代码添加。每个代码都会变成结果中一块带颜色的片段。试试预设,切换时刻和时区,再试试"bug"预设,看一个经典错误。
Try It — strptime Matcherकरके देखें — strptime Matcher动手试试 — strptime 匹配器
strptime walks along the format and the text together. Step through ten real cases and watch which characters each code reads. Every result and error message below is exactly what Python 3.13 gave.
strptime format और text पर साथ-साथ चलता है। दस असली मामलों में कदम-दर-कदम चलें और देखें हर code कौन-से अक्षर पढ़ता है। नीचे का हर नतीजा और error message ठीक वही है जो Python 3.13 ने दिया।
strptime 沿着格式和文本同步前进。逐步查看十个真实案例,看每个代码读取了哪些字符。下面每个结果和错误信息都与 Python 3.13 给出的完全一致。
A common claim is that strptime("2026-7-12", "%Y-%m-%d") fails because the month is not 07. It does not fail — case 3 shows it works. What must match is the order, the separators and the length of the whole text: any extra character gives "unconverted data remains". For messy, unknown formats, the third-party package python-dateutil (dateutil.parser.parse) guesses the layout for you.
एक आम दावा है कि strptime("2026-7-12", "%Y-%m-%d") fail होता है क्योंकि month 07 नहीं है। यह fail नहीं होता — case 3 दिखाता है कि यह चलता है। जो ज़रूर मेल खाना चाहिए वह है क्रम, separators और पूरे text की लंबाई: कोई भी अतिरिक्त अक्षर "unconverted data remains" देता है। बिखरे, अनजान formats के लिए third-party package python-dateutil (dateutil.parser.parse) आपके लिए layout का अंदाज़ा लगाता है।
常有人说 strptime("2026-7-12", "%Y-%m-%d") 会失败,因为月份不是 07。它 不会 失败 — 案例 3 证明它能运行。必须 匹配的是顺序、分隔符和整个文本的长度:任何多余字符都会导致 "unconverted data remains"。对于杂乱、未知的格式,第三方包 python-dateutil(dateutil.parser.parse)会帮你猜测布局。
datetime ↔ Unix Timestamp 🔄datetime ↔ Unix Timestamp 🔄datetime ↔ Unix 时间戳 🔄
datetime → Timestamp with .timestamp().timestamp() से datetime → Timestamp用 .timestamp() 把 datetime 变成时间戳
All the examples from here on were run on a computer set to India time (Asia/Kolkata, UTC+5:30). That matters, as you are about to see.
यहाँ से आगे के सारे उदाहरण भारतीय समय (Asia/Kolkata, UTC+5:30) पर set कंप्यूटर पर चलाए गए। यह मायने रखता है, जैसा आप अभी देखेंगे।
从这里开始的所有示例都在设置为 印度时间(Asia/Kolkata,UTC+5:30) 的电脑上运行。这一点很重要,你马上就会看到。
from datetime import datetime, timezone
aware = datetime(2026, 7, 12, 14, 30, tzinfo=timezone.utc)
ts = aware.timestamp()
print(ts, type(ts).__name__) # a float
print(int(ts))
naive = datetime(2026, 7, 12, 14, 30) # no time zone!
print(int(naive.timestamp())) # Python assumes LOCAL time (here: India, UTC+5:30)
print(int(aware.timestamp()) - int(naive.timestamp())) # 19800 s = 5 h 30 min
The same line, datetime(2026, 7, 12, 14, 30).timestamp(), gives different numbers on a laptop in Delhi, a server in London and a cloud machine set to UTC. That is because a datetime with no tzinfo is treated as the computer's local time. Always attach a time zone before calling .timestamp().
वही line, datetime(2026, 7, 12, 14, 30).timestamp(), Delhi के laptop, London के server और UTC पर set cloud machine पर अलग नंबर देती है। वजह यह है कि बिना tzinfo वाले datetime को कंप्यूटर का local समय माना जाता है। .timestamp() बुलाने से पहले हमेशा time zone जोड़ें।
同一行 datetime(2026, 7, 12, 14, 30).timestamp(),在德里的笔记本、伦敦的服务器和设为 UTC 的云主机上会给出 不同的数字。因为没有 tzinfo 的 datetime 会被当作电脑的本地时间。调用 .timestamp() 之前,务必附上时区。
Timestamp → datetime with fromtimestamp()fromtimestamp() से Timestamp → datetime用 fromtimestamp() 把时间戳变成 datetime
from datetime import datetime, timezone
ts = 1783866600
print(datetime.fromtimestamp(ts)) # local time (this computer: India)
print(datetime.fromtimestamp(ts, tz=timezone.utc)) # UTC - same moment, different clock
Same moment, two clocks: 14:30 in UTC is 20:00 in India. Without tz, you get a naive local time with no label — easy to misread later.
एक ही पल, दो घड़ियाँ: UTC का 14:30 भारत का 20:00 है। tz के बिना आपको बिना label का naive local समय मिलता है — बाद में ग़लत पढ़ना आसान।
同一时刻,两只钟:UTC 的 14:30 就是印度的 20:00。不传 tz,你得到的是没有标签的 naive 本地时间 — 以后很容易读错。
datetime.utcnow() and datetime.utcfromtimestamp() return a naive datetime that holds UTC numbers — so .timestamp() then reads it as local time and gives a wrong answer. Since Python 3.12 they raise a DeprecationWarning. Use datetime.now(timezone.utc) and datetime.fromtimestamp(ts, tz=timezone.utc) instead.
datetime.utcnow() और datetime.utcfromtimestamp() एक naive datetime लौटाते हैं जिसमें UTC के नंबर होते हैं — इसलिए फिर .timestamp() उसे local समय मानकर ग़लत जवाब देता है। Python 3.12 से ये DeprecationWarning देते हैं। इनकी जगह datetime.now(timezone.utc) और datetime.fromtimestamp(ts, tz=timezone.utc) इस्तेमाल करें।
datetime.utcnow() 和 datetime.utcfromtimestamp() 返回装着 UTC 数值的 naive datetime — 随后 .timestamp() 会把它当作本地时间,得出错误答案。从 Python 3.12 起它们会发出 DeprecationWarning。请改用 datetime.now(timezone.utc) 和 datetime.fromtimestamp(ts, tz=timezone.utc)。
The Full Recipe — String ↔ Epoch in One Go 🍳पूरी Recipe — एक बार में String ↔ Epoch 🍳完整配方 — 一步完成字符串 ↔ 纪元 🍳
This is what most people need: a human date straight to a timestamp, and a timestamp from a database straight to any display format. Both are two steps through the datetime hub, and both say clearly that the time is UTC.
ज़्यादातर लोगों को यही चाहिए: इंसानी तारीख़ सीधे timestamp में, और database का timestamp सीधे किसी भी display format में। दोनों datetime hub से होकर दो कदम हैं, और दोनों साफ़ कहते हैं कि समय UTC है।
这是大多数人需要的:把人类日期直接变成时间戳,把数据库里的时间戳直接变成任意显示格式。两者都是经过 datetime 枢纽的两步,并且都明确说明时间是 UTC。
from datetime import datetime, timezone
def to_epoch(text, fmt="%Y-%m-%d %H:%M:%S"):
"""Human-readable string (meant as UTC) -> Unix timestamp."""
dt = datetime.strptime(text, fmt)
dt = dt.replace(tzinfo=timezone.utc) # say clearly: this is UTC
return int(dt.timestamp())
def from_epoch(ts, fmt="%Y-%m-%d %H:%M:%S"):
"""Unix timestamp -> string, shown in UTC."""
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime(fmt)
ts = to_epoch("2026-07-12 14:30:00")
print(ts)
print(to_epoch("12/Jul/2026 14:30", fmt="%d/%b/%Y %H:%M"))
print(to_epoch("2000-01-01 00:00:00")) # Y2K
print(from_epoch(ts))
print(from_epoch(ts, "%A, %d %B %Y at %I:%M %p"))
print(from_epoch(ts, "%d/%m/%Y"))
print(from_epoch(ts, "backup_%Y%m%d_%H%M%S.log"))
Read a timestamp from a database or API → datetime (UTC) → format for display. Read a user's input → parse → attach a time zone → timestamp → save. Learn these two functions and you have covered most practical cases.
Database या API से timestamp पढ़ें → datetime (UTC) → दिखाने के लिए format करें। User का input पढ़ें → parse → time zone जोड़ें → timestamp → save। ये दो functions सीख लें और ज़्यादातर व्यावहारिक मामले हो गए।
从数据库或 API 读取时间戳 → datetime(UTC)→ 格式化显示。读取用户输入 → 解析 → 附加时区 → 时间戳 → 保存。学会这两个函数,你就覆盖了大多数实际场景。
Bonus — ISO 8601 with fromisoformat()Bonus — fromisoformat() के साथ ISO 8601附加 — 用 fromisoformat() 处理 ISO 8601
If the text is in ISO 8601 form (like 2026-07-12T14:30:00Z), you do not need a format string at all. Since Python 3.11, fromisoformat() accepts almost every ISO 8601 form, including the Z for UTC.
अगर text ISO 8601 रूप में है (जैसे 2026-07-12T14:30:00Z), तो format string की ज़रूरत ही नहीं। Python 3.11 से fromisoformat() लगभग हर ISO 8601 रूप स्वीकार करता है, UTC वाले Z समेत।
如果文本是 ISO 8601 格式(如 2026-07-12T14:30:00Z),根本不需要格式字符串。从 Python 3.11 起,fromisoformat() 几乎接受所有 ISO 8601 形式,包括表示 UTC 的 Z。
from datetime import datetime
# Python 3.11+: fromisoformat() reads almost any ISO 8601 string, including "Z"
print(datetime.fromisoformat("2026-07-12T14:30:00Z"))
print(datetime.fromisoformat("2026-07-12T20:00:00+05:30"))
print(datetime.fromisoformat("20260712T143000"))
dt = datetime.fromisoformat("2026-07-12T14:30:00+00:00")
print(dt.isoformat()) # and back again - a safe format for APIs and files
The time Module — Clocks and Stopwatches ⏱️time Module — घड़ियाँ और स्टॉपवॉच ⏱️time 模块 — 时钟与秒表 ⏱️
import time
print(type(time.time()).__name__) # wall clock: float seconds since 1970
start = time.perf_counter() # a stopwatch: only differences matter
time.sleep(0.25)
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.2f}s")
t = time.gmtime(1783866600) # timestamp -> struct_time in UTC
print(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min)
print(time.strftime("%Y-%m-%d %H:%M:%S", t))
print(time.monotonic() > 0) # another clock that never goes backwards
sleep().
सिर्फ़ इस process का CPU time। sleep() को नहीं गिनता।
仅本进程的 CPU 时间。不计入 sleep()。
For small pieces of code, one measurement is noisy. python -m timeit "sorted(range(1000))" runs the code many times and reports the best result — it uses perf_counter() for you.
छोटे code के लिए एक माप में शोर होता है। python -m timeit "sorted(range(1000))" code को कई बार चलाता है और सबसे अच्छा नतीजा बताता है — यह आपके लिए perf_counter() इस्तेमाल करता है।
对小段代码,单次测量噪声很大。python -m timeit "sorted(range(1000))" 会多次运行代码并报告最佳结果 — 它内部替你用了 perf_counter()。
Time Zones — Naive vs Aware 🌍Time Zones — Naive बनाम Aware 🌍时区 — naive 与 aware 🌍
A naive datetime does not know its time zone. An aware datetime does. Mixing the two is the most common source of date bugs, and Python refuses to compare or subtract them.
Naive datetime को अपना time zone नहीं पता। Aware datetime को पता है। दोनों को मिलाना date bugs की सबसे आम वजह है, और Python इनकी तुलना या घटाने से मना करता है।
naive datetime 不知道自己的时区,aware datetime 知道。混用两者是日期 bug 最常见的来源,Python 拒绝比较或相减它们。
| Traitगुण特性 | Detailविवरण说明 |
|---|---|
| tzinfo | None |
| Meansमतलब含义 | whatever the reader guessesजो पढ़ने वाला अंदाज़ा लगाए读者猜什么就是什么 |
| Exampleउदाहरण示例 | datetime(2026, 7, 12, 14, 30) |
| Safe forकिसके लिए सुरक्षित适用于 | a local wall-clock displaylocal घड़ी का display本地挂钟显示 |
| Traitगुण特性 | Detailविवरण说明 |
|---|---|
| tzinfo | timezone.utc, ZoneInfo(...) |
| Meansमतलब含义 | exactly one moment on Earthपृथ्वी पर ठीक एक पल地球上唯一确定的时刻 |
| Exampleउदाहरण示例 | datetime(..., tzinfo=timezone.utc) |
| Safe forकिसके लिए सुरक्षित适用于 | storage, APIs, arithmeticstorage, APIs, गणना存储、API、运算 |
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
naive = datetime(2026, 7, 12, 14, 30)
print(naive, naive.tzinfo)
aware = datetime(2026, 7, 12, 14, 30, tzinfo=timezone.utc)
print(aware, aware.tzinfo)
ist = ZoneInfo("Asia/Kolkata")
print(aware.astimezone(ist)) # same moment, Indian clock
print(aware.astimezone(ZoneInfo("Asia/Shanghai")))
print(aware.astimezone(ZoneInfo("America/New_York")))
fixed = timezone(timedelta(hours=5, minutes=30)) # a fixed offset, no name rules
print(aware.astimezone(fixed))
try:
print(aware - naive)
except TypeError as e:
print("TypeError:", e)
Try It — Time Zone Clockकरके देखें — Time Zone Clock动手试试 — 时区时钟
Six cities, one moment. Slide through a day in 30-minute steps or press Play. Pick 8 March 2026 and watch New York jump from 01:30 to 03:00; pick 1 November 2026 and watch it show 01:30 twice. India, China and Japan have no daylight saving time, so their clocks never jump. All values come from Python's zoneinfo.
छह शहर, एक पल। 30 मिनट के कदमों में दिन पर slide करें या Play दबाएँ। 8 मार्च 2026 चुनें और New York को 01:30 से 03:00 पर कूदते देखें; 1 नवंबर 2026 चुनें और उसे दो बार 01:30 दिखाते देखें। भारत, चीन और जापान में daylight saving time नहीं है, इसलिए उनकी घड़ियाँ कभी नहीं कूदतीं। सारी values Python के zoneinfo से आई हैं।
六座城市,同一时刻。以 30 分钟为步长拖过一天,或按 播放。选 2026 年 3 月 8 日,看纽约从 01:30 跳到 03:00;选 2026 年 11 月 1 日,看它两次显示 01:30。印度、中国和日本没有夏令时,所以时钟从不跳变。所有数值都来自 Python 的 zoneinfo。
Daylight Saving: Times That Do Not Exist, and Times That Happen TwiceDaylight Saving: जो समय होते ही नहीं, और जो दो बार होते हैं夏令时:不存在的时间,和出现两次的时间
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
# 8 March 2026: New York clocks jump from 02:00 straight to 03:00
gap = datetime(2026, 3, 8, 2, 30, tzinfo=ny)
print(gap.astimezone(ZoneInfo("UTC")).astimezone(ny)) # 02:30 does not exist
# 1 November 2026: clocks go back, so 01:30 happens TWICE
first = datetime(2026, 11, 1, 1, 30, tzinfo=ny, fold=0)
second = datetime(2026, 11, 1, 1, 30, tzinfo=ny, fold=1)
print(first, first.tzname())
print(second, second.tzname())
print(second.timestamp() - first.timestamp()) # 3600.0 seconds apart
fold=0 picks the first 01:30 (still summer time, EDT), fold=1 the second one (winter time, EST). They are one hour apart, though the wall clock reads the same.
fold=0 पहला 01:30 चुनता है (अब भी गर्मी का समय, EDT), fold=1 दूसरा (सर्दी का समय, EST)। दीवार की घड़ी एक ही समय दिखाती है, फिर भी ये एक घंटे के अंतर पर हैं।
fold=0 选择第一个 01:30(仍是夏令时 EDT),fold=1 选择第二个(冬令时 EST)。挂钟读数相同,实际却相差一小时。
Linux and macOS ship a time zone database, and zoneinfo uses it. Windows does not, so ZoneInfo("Asia/Kolkata") raises ZoneInfoNotFoundError until you run pip install tzdata. For a fixed offset with no rules, timezone(timedelta(hours=5, minutes=30)) always works.
Linux और macOS के साथ time zone database आता है, और zoneinfo उसे इस्तेमाल करता है। Windows के साथ नहीं, इसलिए ZoneInfo("Asia/Kolkata") तब तक ZoneInfoNotFoundError देता है जब तक आप pip install tzdata न चलाएँ। बिना नियमों वाले तय offset के लिए timezone(timedelta(hours=5, minutes=30)) हमेशा चलता है।
Linux 和 macOS 自带时区数据库,zoneinfo 会使用它。Windows 没有,所以在运行 pip install tzdata 之前,ZoneInfo("Asia/Kolkata") 会抛出 ZoneInfoNotFoundError。若只需固定偏移、无需规则,timezone(timedelta(hours=5, minutes=30)) 总能用。
Time Arithmetic with timedelta ➕timedelta से समय की गणना ➕用 timedelta 做时间运算 ➕
A timedelta is a duration. Add it to a datetime to move forward, subtract it to move back. Subtracting two datetimes gives a timedelta.
timedelta एक अवधि है। आगे जाने के लिए इसे datetime में जोड़ें, पीछे जाने के लिए घटाएँ। दो datetimes घटाने पर timedelta मिलता है।
timedelta 表示一段 时长。加到 datetime 上向前移动,减去则向后移动。两个 datetime 相减得到 timedelta。
from datetime import datetime, timedelta
now = datetime(2026, 7, 12, 14, 30) # a fixed "now"
print(now + timedelta(days=1))
print(now + timedelta(weeks=1))
print(now + timedelta(minutes=90))
print(now - timedelta(days=1))
custom = timedelta(days=2, hours=3, minutes=30, seconds=45)
print(custom) # str: "2 days, 3:30:45"
print(repr(custom)) # stored as days + seconds only
print(now + custom)
print(timedelta(hours=-1)) # negative: -1 day + 23 hours!
until = datetime(2026, 12, 25) - now
print(f"Days until Christmas: {until.days}")
print(f"Total seconds: {until.total_seconds():.0f}")
Try It — timedelta Calculatorकरके देखें — timedelta Calculator动手试试 — timedelta 计算器
Type weeks, days, hours and minutes (negative numbers too). Watch how Python stores and prints the result, and where it lands on the ±30-day ruler.
Weeks, days, hours और minutes लिखें (negative नंबर भी)। देखें Python नतीजे को कैसे रखता और छापता है, और वह ±30 दिन के पैमाने पर कहाँ पहुँचता है।
输入周、天、小时和分钟(也可以是负数)。看看 Python 如何存储和打印结果,以及它落在 ±30 天尺子上的哪里。
Months and years have different lengths, so timedelta only knows fixed units (weeks, days, hours, minutes, seconds, milliseconds, microseconds). To add "one month", use dateutil.relativedelta(months=1) from python-dateutil, or work out the month yourself.
महीनों और सालों की लंबाई अलग-अलग होती है, इसलिए timedelta सिर्फ़ तय इकाइयाँ जानता है (weeks, days, hours, minutes, seconds, milliseconds, microseconds)। "एक महीना" जोड़ने के लिए python-dateutil का dateutil.relativedelta(months=1) इस्तेमाल करें, या महीना ख़ुद गिनें।
月和年的长度不固定,所以 timedelta 只认识固定单位(周、天、小时、分钟、秒、毫秒、微秒)。要加"一个月",请用 python-dateutil 的 dateutil.relativedelta(months=1),或自己计算月份。
Practical Real-World Examples 🛠️असली काम के उदाहरण 🛠️实战示例 🛠️
Each example takes "today" or "now" as an argument instead of reading the clock inside. That makes the function easy to test — and the output below repeatable.
हर उदाहरण घड़ी को अंदर पढ़ने के बजाय "today" या "now" को argument के रूप में लेता है। इससे function को test करना आसान होता है — और नीचे का output दोहराने योग्य रहता है।
每个示例都把"今天"或"现在"作为参数传入,而不是在函数内部读时钟。这样函数容易测试 — 下面的输出也可重复。
1 · Age from Date of Birth1 · जन्मतिथि से उम्र1 · 根据出生日期计算年龄
from datetime import date
def age(dob_text, today):
dob = date.fromisoformat(dob_text)
years = today.year - dob.year
if (today.month, today.day) < (dob.month, dob.day): # birthday not yet this year
years -= 1
return years
today = date(2026, 7, 12)
print(age("1990-03-15", today)) # birthday already passed
print(age("1990-11-20", today)) # birthday still to come
2 · Countdown2 · उलटी गिनती2 · 倒计时
from datetime import datetime
def countdown(target_text, now):
target = datetime.strptime(target_text, "%Y-%m-%d %H:%M")
delta = target - now
if delta.total_seconds() < 0:
return "That moment has passed!"
hours, rem = divmod(delta.seconds, 3600)
return f"{delta.days}d {hours}h {rem // 60}m remaining"
now = datetime(2026, 7, 12, 14, 30)
print(countdown("2026-12-31 23:59", now))
print(countdown("2026-01-01 00:00", now))
3 · Parse Log Timestamps3 · Log Timestamps parse करना3 · 解析日志时间戳
from datetime import datetime
log_lines = [
"[2026-07-12 14:30:15] User logged in",
"[2026-07-12 14:31:02] File uploaded",
"[2026-07-12 14:35:47] Session expired",
]
events = []
for line in log_lines:
stamp, message = line[1:20], line[22:]
events.append((datetime.strptime(stamp, "%Y-%m-%d %H:%M:%S"), message))
for (t1, m1), (t2, m2) in zip(events, events[1:]):
print(f"{m1!r} -> {m2!r}: {t2 - t1}")
duration = events[-1][0] - events[0][0]
print(f"Session lasted {duration.total_seconds():.0f} seconds ({duration})")
4 · Between an API and a User4 · API और User के बीच4 · 在 API 与用户之间
from datetime import datetime, timezone
# An API sent this JSON: {"created_at": 1783866600}
created = datetime.fromtimestamp(1783866600, tz=timezone.utc)
print(f"Created: {created.strftime('%d %b %Y, %H:%M UTC')}")
# A user typed "31/12/2026" - save it as a UTC timestamp
dt_user = datetime.strptime("31/12/2026", "%d/%m/%Y").replace(tzinfo=timezone.utc)
epoch_to_save = int(dt_user.timestamp())
print(f"Saving: {epoch_to_save}")
print("Check :", datetime.fromtimestamp(epoch_to_save, tz=timezone.utc))
5 · Timestamped File Names5 · Timestamp वाले File नाम5 · 带时间戳的文件名
from datetime import datetime
now = datetime(2026, 7, 12, 14, 30, 15)
print(now.strftime("export_%Y%m%d_%H%M%S.csv"))
print(now.strftime("backup-%Y-%m-%d.tar.gz"))
# Names in this format sort in time order, even as plain text
names = ["export_20261201.csv", "export_20260712.csv", "export_20260105.csv"]
print(sorted(names))
6 · Dates Without a Year — A Change in Python 3.156 · बिना साल की तारीख़ें — Python 3.15 में बदलाव6 · 没有年份的日期 — Python 3.15 的变化
import warnings
from datetime import datetime
warnings.simplefilter("always") # show the warning every time
# Day and month, but NO year:
try:
print(datetime.strptime("29 Feb", "%d %b"))
except ValueError as e:
print("ValueError:", e)
# The fix: add a leap year yourself, then use only day and month
d = datetime.strptime("29 Feb 2000", "%d %b %Y")
print(d.day, d.month)
Without a year, strptime uses 1900 — which is not a leap year, so "29 Feb" fails. Python 3.13 and 3.14 show a DeprecationWarning, as above. Python 3.15 goes further: any format with %d but no year raises ValueError, even for 12 July. The fix works on every version: add a leap year such as 2000 to both the text and the format.
साल के बिना strptime 1900 लेता है — जो leap year नहीं है, इसलिए "29 Feb" fail होता है। Python 3.13 और 3.14 ऊपर की तरह DeprecationWarning दिखाते हैं। Python 3.15 और आगे जाता है: %d वाला पर बिना साल का कोई भी format ValueError देता है, 12 जुलाई के लिए भी। हल हर version पर चलता है: text और format दोनों में 2000 जैसा कोई leap year जोड़ें।
没有年份时,strptime 使用 1900 年 — 它 不是 闰年,所以"29 Feb"会失败。Python 3.13 和 3.14 会像上面那样显示 DeprecationWarning。Python 3.15 更进一步:任何含 %d 但没有年份的格式都会抛出 ValueError,即使是 7 月 12 日。修复方法在所有版本都有效:在文本和格式中都加上一个闰年,比如 2000。
Before 3.14 you wrote datetime.strptime(text, "%Y-%m-%d").date(). Python 3.14 adds date.strptime() and time.strptime() class methods, so you can parse straight into a date or a time.
3.14 से पहले आप datetime.strptime(text, "%Y-%m-%d").date() लिखते थे। Python 3.14 date.strptime() और time.strptime() class methods जोड़ता है, ताकि आप सीधे date या time में parse कर सकें।
在 3.14 之前你要写 datetime.strptime(text, "%Y-%m-%d").date()。Python 3.14 新增了 date.strptime() 和 time.strptime() 类方法,可以直接解析成 date 或 time。
Common Pitfalls 🕳️आम ग़लतियाँ 🕳️常见陷阱 🕳️
TypeError. Use aware UTC datetimes everywhere inside your program.TypeError आता है। Program के अंदर हर जगह aware UTC datetimes रखें।TypeError。程序内部请处处使用 aware 的 UTC datetime。%m is the month, uppercase %M the minute. A swap gives plausible wrong dates and no error — see case 9 in the Matcher.%m month है, बड़ा %M minute। उलटने पर सही-से दिखने वाली ग़लत तारीख़ें और कोई error नहीं — Matcher का case 9 देखें।%m 是月份,大写 %M 是分钟。写反会得到看似合理的错误日期,而且 不报错 — 见匹配器的案例 9。datetime.now(timezone.utc).datetime.now(timezone.utc) इस्तेमाल करें।datetime.now(timezone.utc)。strptime accepts 7 for %m, but one extra space or character gives "unconverted data remains". Strip input first.strptime %m के लिए 7 स्वीकार करता है, पर एक भी अतिरिक्त space या अक्षर "unconverted data remains" देता है। पहले input strip करें।strptime 接受 7 作为 %m,但多一个空格或字符就会 "unconverted data remains"。请先 strip 输入。fold). Do arithmetic in UTC and convert at the end.fold)। गणना UTC में करें और अंत में बदलें।fold)。在 UTC 中做运算,最后再转换。Quick Reference, Golden Rules and Quiz 🏆झटपट संदर्भ, सुनहरे नियम और Quiz 🏆速查、黄金法则与小测验 🏆
| CallCall调用 | What it doesक्या करता है作用 |
|---|---|
datetime.now(timezone.utc) | current moment, aware UTCमौजूदा पल, aware UTC当前时刻,aware UTC |
datetime.strptime(s, fmt) | string → datetimestring → datetime字符串 → datetime |
dt.strftime(fmt) | datetime → stringdatetime → stringdatetime → 字符串 |
datetime.fromisoformat(s) | ISO 8601 string → datetimeISO 8601 string → datetimeISO 8601 字符串 → datetime |
dt.isoformat() | datetime → ISO 8601 stringdatetime → ISO 8601 stringdatetime → ISO 8601 字符串 |
dt.timestamp() | datetime → float timestampdatetime → float timestampdatetime → 浮点时间戳 |
datetime.fromtimestamp(ts, timezone.utc) | timestamp → aware datetimetimestamp → aware datetime时间戳 → aware datetime |
dt.replace(tzinfo=timezone.utc) | label a naive time as UTCnaive समय पर UTC का label给 naive 时间标上 UTC |
dt.astimezone(ZoneInfo(name)) | same moment, another clockवही पल, दूसरी घड़ी同一时刻,换一只钟 |
dt + timedelta(days=1) | move in timeसमय में आगे-पीछे在时间上移动 |
time.time() | current timestampमौजूदा timestamp当前时间戳 |
time.perf_counter() | measure durationsअवधि नापना测量时长 |
strptime: string → datetime. strftime: datetime → string.strptime: string → datetime। strftime: datetime → string।strptime:字符串 → datetime。strftime:datetime → 字符串。%m month, %M minute; %H 24-hour, %I 12-hour (needs %p).%m month, %M minute; %H 24-घंटे, %I 12-घंटे (%p चाहिए)।%m 月份,%M 分钟;%H 24 小时制,%I 12 小时制(需要 %p)。time.time() for timestamps, time.perf_counter() for durations. The wall clock can jump; the stopwatch cannot.time.time(), अवधि के लिए time.perf_counter()। Wall clock कूद सकती है; स्टॉपवॉच नहीं।time.time(),时长用 time.perf_counter()。挂钟会跳,秒表不会。isoformat() / fromisoformat()) for files and APIs. It sorts as text and needs no format string.isoformat() / fromisoformat())। यह text के रूप में sort होता है और format string नहीं चाहिए।isoformat() / fromisoformat())。它按文本排序即有序,也无需格式字符串。Quick Quiz — 8 Questionsछोटा Quiz — 8 सवाल小测验 — 8 道题
A moment has three faces — string, datetime and timestamp — and the datetime is the hub between them. Parse with strptime (or fromisoformat), format with strftime, convert with .timestamp() and fromtimestamp(ts, tz). Keep everything aware and in UTC inside your program, use zoneinfo at the edges, timedelta for durations, and perf_counter() to time your code.
एक पल के तीन चेहरे हैं — string, datetime और timestamp — और datetime इनके बीच का hub है। strptime (या fromisoformat) से parse करें, strftime से format करें, .timestamp() और fromtimestamp(ts, tz) से बदलें। Program के अंदर सब कुछ aware और UTC में रखें, किनारों पर zoneinfo, अवधि के लिए timedelta, और code का समय नापने के लिए perf_counter() इस्तेमाल करें।
一个时刻有三张面孔 — 字符串、datetime 和时间戳 — datetime 是它们之间的枢纽。用 strptime(或 fromisoformat)解析,用 strftime 格式化,用 .timestamp() 和 fromtimestamp(ts, tz) 转换。程序内部一律保持 aware 和 UTC,在边界使用 zoneinfo,时长用 timedelta,计时用 perf_counter()。