Hướng dẫn python datetime adjust

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
  • Example 1: datetime to string using strftime()
  • How strftime() works?
  • Example 2: Creating string from a timestamp
  • Format Code List
  • Example 3: Locale's appropriate date and time
  • How do I change date format from YYYY MM DD in Python?
  • How do you change a date format from a string in Python?
  • How do I convert datetime to date format?
  • How do I change the date format from YYYY MM DD in pandas?

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

Possible Duplicate:
How to convert a time to a string

Nội dung chính

  • Example 1: datetime to string using strftime()
  • How strftime() works?
  • Example 2: Creating string from a timestamp
  • Format Code List
  • Example 3: Locale's appropriate date and time
  • How do I change date format from YYYY MM DD in Python?
  • How do you change a date format from a string in Python?
  • How do I convert datetime to date format?
  • How do I change the date format from YYYY MM DD in pandas?

I have a variable as shown in the below code.

a = "2011-06-09"

Using python, how to convert it to the following format?

"Jun 09,2011"

asked Jun 9, 2011 at 6:27

2

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

answered Jun 9, 2011 at 6:30

NPENPE

470k103 gold badges921 silver badges994 bronze badges

1

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

answered Jun 9, 2011 at 6:31

mgiucamgiuca

20.6k6 gold badges52 silver badges70 bronze badges

1

The strftime() method returns a string representing date and time using date, time or datetime object.


Example 1: datetime to string using strftime()

The program below converts a datetime object containing current date and time to different string formats.


from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)	

When you run the program, the output will something like be:

year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:31

Here, year, day, time and date_time are strings, whereas now is a datetime object.


How strftime() works?

In the above program, %Y, %m, %d etc. are format codes. The strftime() method takes one or more format codes as an argument and returns a formatted string based on it.

  1. We imported datetime class from the datetime module. It's because the object of datetime class can access strftime() method.
  2. The datetime object containing current date and time is stored in now variable.
  3. The strftime() method can be used to create formatted strings.
  4. The string you pass to the strftime() method may contain more than one format codes.

Example 2: Creating string from a timestamp


from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

print("Date time object:", date_time)

d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("Output 2:", d)	

d = date_time.strftime("%d %b, %Y")
print("Output 3:", d)

d = date_time.strftime("%d %B, %Y")
print("Output 4:", d)

d = date_time.strftime("%I%p")
print("Output 5:", d)

When you run the program, the output will be:

Date time object: 2018-06-12 09:55:22
Output 2: 06/12/2018, 09:55:22
Output 3: 12 Jun, 2018
Output 4: 12 June, 2018
Output 5: 09AM

Format Code List

The table below shows all the codes that you can pass to the strftime() method.

Directive Meaning Example
%a Abbreviated weekday name. Sun, Mon, ...
%A Full weekday name. Sunday, Monday, ...
%w Weekday as a decimal number. 0, 1, ..., 6
%d Day of the month as a zero-padded decimal. 01, 02, ..., 31
%-d Day of the month as a decimal number. 1, 2, ..., 30
%b Abbreviated month name. Jan, Feb, ..., Dec
%B Full month name. January, February, ...
%m Month as a zero-padded decimal number. 01, 02, ..., 12
%-m Month as a decimal number. 1, 2, ..., 12
%y Year without century as a zero-padded decimal number. 00, 01, ..., 99
%-y Year without century as a decimal number. 0, 1, ..., 99
%Y Year with century as a decimal number. 2013, 2019 etc.
%H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, ..., 23
%-H Hour (24-hour clock) as a decimal number. 0, 1, ..., 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, ..., 12
%-I Hour (12-hour clock) as a decimal number. 1, 2, ... 12
%p Locale’s AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, ..., 59
%-M Minute as a decimal number. 0, 1, ..., 59
%S Second as a zero-padded decimal number. 00, 01, ..., 59
%-S Second as a decimal number. 0, 1, ..., 59
%f Microsecond as a decimal number, zero-padded on the left. 000000 - 999999
%z UTC offset in the form +HHMM or -HHMM.  
%Z Time zone name.  
%j Day of the year as a zero-padded decimal number. 001, 002, ..., 366
%-j Day of the year as a decimal number. 1, 2, ..., 366
%U Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, ..., 53
%W Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, ..., 53
%c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
%x Locale’s appropriate date representation. 09/30/13
%X Locale’s appropriate time representation. 07:06:05
%% A literal '%' character. %

Example 3: Locale's appropriate date and time


from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

d = date_time.strftime("%c")
print("Output 1:", d)	

d = date_time.strftime("%x")
print("Output 2:", d)

d = date_time.strftime("%X")
print("Output 3:", d)

When you run the program, the output will be:

Output 1: Tue Jun 12 09:55:22 2018
Output 2: 06/12/18
Output 3: 09:55:22

Format codes %c, %x and %X are used for locale's appropriate date and time representation.


We also recommend you to check Python strptime(). The strptime() method creates a datetime object from a string.

How do I change date format from YYYY MM DD in Python?

We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime..

input is the string datetime..

format is the format – 'yyyy-mm-dd'.

datetime is the module..

How do you change a date format from a string in Python?

from datetime import datetime..

date_time_str = '18/09/19 01:55:19'.

date_time_obj = datetime. strptime(date_time_str, '%d/%m/%y %H:%M:%S').

print ("The type of the date is now", type(date_time_obj)).

How do I convert datetime to date format?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

How do I change the date format from YYYY MM DD in pandas?

import pandas as pd. # input in mm.dd.yyyy format. date = ['01.02.2019'] ... .

import pandas as pd. # date (mm.dd.yyyy) and time (H:MM:SS) date = ['01.02.2019 1:30:00 PM'] ... .

import pandas as pd. # pandas interprets this date to be in m-d-yyyy format. print(pd. ... .

import pandas as pd. date = '2019-07-31 12:00:00-UTC' print(pd..