Hướng dẫn datetime utc python

Tổng quan

Gần đây mình có làm việc nhiều với kiểu dữ liệu Datetime trong Python. Vấn đề mình gặp phải là xử lý nhiều loại time format khác nhau, chuyển hóa thành dạng Datetime, chuẩn hóa thời gian lưu trữ và lưu vào database. Và sau đây, mình sẽ viết bài chia sẻ về cách mình xử lý kiểu dữ liệu Datetime trong Python. Trong bài mình sẽ sử dụng Python 3 để xử lý kiểu dữ liệu Datetime.

Nội dung chính

  • Tổng quan
  • Tips 1: Chuẩn hóa múi giờ sử dụng
  • Tips 2: Convert String thành Datetime
  • Tips 3: Chuyển hóa kiểu Datetime sang Timestamp Python
  • Tips 4: Chuyển hóa kiểu native date sang UTC timezone
  • Tips 5: Convert UTC sang timezone khác
  • Tips 6: Chuyên từ Timestamp sang Datetime
  • Tips 7: Convert Datetime sang ISO 8601
  • Timezone aware with zero external dependencies:

Tips 1: Chuẩn hóa múi giờ sử dụng

Đầu tiên, cũng là quan trọng nhất, chuẩn hóa múi giờ sử dụng để convert các kiểu thời gian. Mình lựa chọn sử dụng chuẩn múi giờ UTC để chuẩn hóa thời gian cho cả hệ thống cũng như làm múi giờ chuẩn để xử lý các loại format thời gian khác nhau.

Tham khảo thêm về thời gian UTC tại

Tips 2: Convert String thành Datetime

Xử lý bằng hàm parse

import datetime
import pytz
from dateutil.parser import parse

# Dạng string time
date_string = '2019-03-20T03:41:16Z'

# Dạng datetime format
date_time_python = parse(date_string)

Xử lý bằng strptime

import datetime
import pytz
from dateutil.parser import parse

# Dạng string time
date_string = '2019-03-21 03:41:16'

# Strptime
format = '%Y-%m-%d %H:%M:%S'
date_time_python = datetime.datetime.strptime(date_string, format)

Lưu ý:

  • Các rất nhiều format time khác nhau nên để có thể chuyển từ string thành Datetime parse chỉ có thể xử lý một số dạng tiêu chuẩn, nếu khác dạng tiêu chuẩn phải hiểu ra cấu trúc time string để sử dụng hàm strp để cắt chuỗi tạo Datetime
  • Nếu kiểu dữ liệu Datetime không rõ múi giờ thì được gọi là native date

Tips 3: Chuyển hóa kiểu Datetime sang Timestamp Python

Timestamp là kiểu thời gian thông dụng của hệ thông Unix, tìm hiểu thêm tại

import datetime

# Dạng datetime
date_time_now = datetime.datetime.now()

# Dạng timestamp
timestamp_now = date_time_now.timestamp()

Tips 4: Chuyển hóa kiểu native date sang UTC timezone

Kiểm tra kiểu timezone

import datetime
import pytz

# Dạng native date
date_time_now = datetime.datetime.now()
print(date_time_now.tzname())

# Dạng utc
UTC = pytz.utc
date_time_utc_now = UTC.localize(date_time_now)
print(date_time_utc_now.tzname())

Lưu ý: không sử dụng hàm replace, hàm replace sẽ chỉ thay đổi tzinfo không qui đổi thời gian từ múi giờ này sang múi giờ khác

Tips 5: Convert UTC sang timezone khác

Nếu bạn ở múi giờ Việt Nam (GMT + 7), tức nếu hiện tại là 8 giờ sáng (giờ Việt Nam) thì quy ra giờ UTC tức 1 giờ sáng (giờ UTC). Vậy nếu Datetime đang ở múi giờ UTC, ta phải convert nó sáng giờ Việt Nam

import datetime
import pytz

# Dạng native date
date_time_now = datetime.datetime.now()
print(date_time_now.tzname())

# Dạng utc
UTC = pytz.utc
date_time_utc_now = UTC.localize(date_time_now)
print(date_time_utc_now.tzname())

# Dạng 'Asia/Ho_Chi_Minh'

VN_TZ = pytz.timezone('Asia/Ho_Chi_Minh')
date_time_vntz_now = date_time_utc_now.astimezone(VN_TZ)
print(date_time_vntz_now.tzname())

Tips 6: Chuyên từ Timestamp sang Datetime

import datetime

date_time_now = datetime.datetime.now()
timestamp_now = date_time_now.timestamp()

# Convert timestamp thành dạng Datetime
timestamp_to_datetime = datetime.datetime.fromtimestamp(timestamp_now)

Tips 7: Convert Datetime sang ISO 8601

ISO 8601 là một tiêu chuẩn quốc tế, được đưa ra bởi Tổ chức tiêu chuẩn hóa quốc tế (ISO) lần đầu tiên năm 1988, mô tả quy cách viết ngày tháng và thời gian theo cách đơn giản nhất mà máy tính có thể hiểu được. Còn đối với Python ISO 8601 Datetime là string format time thông dụng.

import datetime

date_time_now = datetime.datetime.now()

# Convert Datetime thành dạng ISO 8601
iso_format = date_time_now.isoformat()

Nguồn

https://vi.wikipedia.org/wiki/Th%E1%BA%A3o_lu%E1%BA%ADn:M%C3%BAi_gi%E1%BB%9D

https://vi.wikipedia.org/wiki/Th%E1%BA%A3o_lu%E1%BA%ADn:M%C3%BAi_gi%E1%BB%9D


Thực hiện bởi cloud365.vn

How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

asked Apr 11, 2013 at 3:33

James ClarkeJames Clarke

2,1072 gold badges12 silver badges3 bronze badges

3

Use datetime.utcnow():

from datetime import datetime
datetime.utcnow()

For your purposes when you need to calculate an amount of time spent between two dates all that you need is to subtract end and start dates. The results of such subtraction is a timedelta object.

From the python docs:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 106) / 106 computed with true division enabled.

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Apr 11, 2013 at 3:35

Artsiom RudzenkaArtsiom Rudzenka

27k4 gold badges32 silver badges51 bronze badges

2

Timezone-aware datetime object, unlike datetime.utcnow():

from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)

Timestamp in milliseconds since Unix epoch:

datetime.now(timezone.utc).timestamp() * 1000

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Oct 8, 2019 at 22:34

Tim RichardsonTim Richardson

5,6176 gold badges42 silver badges63 bronze badges

4

In the form closest to your original:

import datetime

def UtcNow():
    now = datetime.datetime.utcnow()
    return now

If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:

return (now - datetime.datetime(1970, 1, 1)).total_seconds()

Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:

utc_now = datetime.datetime.utcnow

answered Apr 11, 2013 at 3:36

Mark RansomMark Ransom

290k40 gold badges383 silver badges606 bronze badges

13

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

answered Sep 3, 2018 at 8:56

1

Timezone aware with zero external dependencies:

from datetime import datetime, timezone

def utc_now():
    return datetime.utcnow().replace(tzinfo=timezone.utc)

answered Feb 25, 2019 at 16:05

Cesar CanassaCesar Canassa

17k9 gold badges64 silver badges68 bronze badges

3

From datetime.datetime you already can export to timestamps with method strftime. Following your function example:

import datetime
def UtcNow():
    now = datetime.datetime.utcnow()
    return int(now.strftime("%s"))

If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))

answered Mar 21, 2017 at 17:19

hectorcantohectorcanto

1,76713 silver badges17 bronze badges

3

you could use datetime library to get UTC time even local time.

import datetime

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

answered Feb 19, 2021 at 6:41

HCHOHCHO

951 silver badge5 bronze badges

why all reply based on datetime and not time? i think is the easy way !

import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)

answered Aug 28, 2021 at 14:14

1