Hướng dẫn python datetime shift days - python datetime shift ngày

All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.

Proposed solution

The following solution works for Samoa and keeps the local time constant.

def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz

Tested Code

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))

Test results

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1

Tổng Quan

Gần Đây Mình Có Lào Việc Nhiều Với Kiểu Dữ Liệu Datetime Trong Python. Vấn Đề Mình 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ào mình sẽ sử dụng python 3 để xử lý kiểu dữ liệu datetime.

Nội phân chính

  • Tổng Quan
  • Gần Đây Mình Có Lào Việc Nhiều Với Kiểu Dữ Liệu Datetime Trong Python. Vấn Đề Mình 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ào mình sẽ sử dụng python 3 để xử lý kiểu dữ liệu datetime.
  • Nội phân chính
  • Mẹo 1: Chuẩn Hón muy gi ử sử dụng
  • Mẹo 2: Chuyển đổi Chuỗi ThànH DateTime
  • Mẹo 3: Chuyển HùaA Kiểu DateTime Sang Timestamp Python
  • Lời khuyên 4: Chuyển Hón Kiểu Ngày bản địa hát UTC Timezone
  • Mẹo 5: Chuyển đổi UTC Sang Timezone Khác
  • Mẹo 6: Chuyên từ Timestamp Sang DateTime
  • Mẹo 7: Chuyển đổi DateTime Sang ISO 8601
  • Ví dụ 1: DateTime to String bằng cách sử dụng strftime ()
  • Làm thế nào strftime () hoạt động?
  • Ví dụ 3: Ngày và giờ thích hợp của địa phương
  • Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong python?
  • Làm thế nào để bạn thay đổi định dạng ngày từ một chuỗi trong Python?
  • Làm cách nào để chuyển đổi DateTime sang định dạng ngày?
  • Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong gấu trúc?

Nội phân chính

  • Tổng Quan
  • Gần Đây Mình Có Lào Việc Nhiều Với Kiểu Dữ Liệu Datetime Trong Python. Vấn Đề Mình 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ào mình sẽ sử dụng python 3 để xử lý kiểu dữ liệu datetime.
  • Nội phân chính
  • Mẹo 1: Chuẩn Hón muy gi ử sử dụng
  • Mẹo 2: Chuyển đổi Chuỗi ThànH DateTime
  • Mẹo 3: Chuyển HùaA Kiểu DateTime Sang Timestamp Python
  • Lời khuyên 4: Chuyển Hón Kiểu Ngày bản địa hát UTC Timezone
  • Mẹo 5: Chuyển đổi UTC Sang Timezone Khác
  • Mẹo 6: Chuyên từ Timestamp Sang DateTime
  • Mẹo 7: Chuyển đổi DateTime Sang ISO 8601
  • Ví dụ 1: DateTime to String bằng cách sử dụng strftime ()
  • Làm thế nào strftime () hoạt động?
  • Ví dụ 3: Ngày và giờ thích hợp của địa phương
  • Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong python?
  • Làm thế nào để bạn thay đổi định dạng ngày từ một chuỗi trong Python?
  • Làm cách nào để chuyển đổi DateTime sang định dạng ngày?
  • Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong gấu trúc?

Gần Đây Mình Có Lào Việc Nhiều Với Kiểu Dữ Liệu Datetime Trong Python. Vấn Đề Mình 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ào mình sẽ sử dụng python 3 để xử lý kiểu dữ liệu datetime.

Nội phân chính

Mẹo 1: Chuẩn Hón muy gi ử sử dụng

Nội phân chính

Mẹo 1: Chuẩn Hón muy gi ử sử dụng

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)

Mẹo 2: Chuyển đổi Chuỗi ThànH DateTime

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)

Mẹo 3: Chuyển HùaA Kiểu DateTime Sang Timestamp Python

  • Lời khuyên 4: Chuyển Hón Kiểu Ngày bản địa hát UTC Timezone
  • Mẹo 5: Chuyển đổi UTC Sang Timezone Khác

Mẹo 1: Chuẩn Hón muy gi ử sử dụng

Mẹo 2: Chuyển đổi Chuỗi ThànH DateTime

import datetime

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

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

Mẹo 2: Chuyển đổi Chuỗi ThànH DateTime

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

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
4 variable as shown in the below code.

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
0

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

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
1

asked Jun 9, 2011 at 6:27Jun 9, 2011 at 6:27

2

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
2

In pre-2.5 Python, you can replace

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
5 with
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
6, like so (untested):
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
7

answered Jun 9, 2011 at 6:30Jun 9, 2011 at 6:30

NPENPENPE

470k103 gold badges921 silver badges994 bronze badges103 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:

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
3

answered Jun 9, 2011 at 6:31Jun 9, 2011 at 6:31

mgiucamgiucamgiuca

20.6k6 gold badges52 silver badges70 bronze badges6 gold badges52 silver badges70 bronze badges

1

The

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method returns a string representing date and time using date, time or datetime object.


Example 1: datetime to string using strftime()

How strftime() works?

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
4

Example 2: Creating string from a timestamp

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
5

Format Code List


How strftime() works?

Example 2: Creating string from a timestamp

  1. Format Code List
  2. Example 3: Locale's appropriate date and time
  3. How do I change date format from YYYY MM DD in Python?
  4. How do you change a date format from a string in Python?

Example 2: Creating string from a timestamp

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
6

Format Code List

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
7

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
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
4 variable as shown in the below code.
Using python, how to convert it to the following format?
asked Jun 9, 2011 at 6:27In pre-2.5 Python, you can replace
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
5 with
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
6, like so (untested):
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
7
answered Jun 9, 2011 at 6:30
NPENPE470k103 gold badges921 silver badges994 bronze badges@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: answered Jun 9, 2011 at 6:31mgiucamgiuca
20.6k6 gold badges52 silver badges70 bronze badgesThe
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method returns a string representing date and time using date, time or datetime object.
The program below converts a 
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 object containing current date and time to different string formats.
When you run the program, the output will something like be:Here, year, day, time and date_time are strings, whereas now is a
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 object.
In the above program,
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)
1,
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)
2,
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)
3 etc. are format codes. The
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method takes one or more format codes as an argument and returns a formatted string based on it.
We imported
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 class from the
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 module. It's because the object of
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 class can access
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method.
The
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 object containing current date and time is stored in now variable.
The
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method can be used to create formatted strings.
The string you pass to the
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method may contain more than one format codes.
When you run the program, the output will be:The table below shows all the codes that you can pass to the
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method.
DirectiveMeaningExample
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)
3
Abbreviated weekday name. Sun, Mon, ...
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)
4
Full weekday name. Sunday, Monday, ...
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)
5
Weekday as a decimal number. 0, 1, ..., 6
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)
3
Day of the month as a zero-padded decimal. 01, 02, ..., 31
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)
7
Day of the month as a decimal number. 1, 2, ..., 30
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)
8
Abbreviated month name. The table below shows all the codes that you can pass to the
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
8 method.
DirectiveMeaningExample
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)
3
Abbreviated weekday name. Sun, Mon, ...
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)
4
Full weekday name. Sunday, Monday, ...
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)
5
Weekday as a decimal number. 0, 1, ..., 6
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)
3
Day of the month as a zero-padded decimal. Sunday, Monday, ...
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)
5
Weekday as a decimal number. 0, 1, ..., 59
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())
4
Microsecond như một số thập phân, không được dán bên trái.000000 - 999999
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())
5
UTC bù ở dạng +hhmm hoặc -hhmm.& nbsp;
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())
6
Tên múi giờ.& nbsp;
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())
6
Tên múi giờ.
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())
7
Ngày trong năm dưới dạng số thập phân không có viền.001, 002, ..., 366
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())
8
Ngày trong năm dưới dạng số thập phân.1, 2, ..., 366
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())
9
Số tuần của năm (Chủ nhật là ngày đầu tiên của tuần). Tất cả các ngày trong một năm mới trước Chủ nhật đầu tiên được coi là vào tuần 0.00, 01, ..., 53
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())
9
Số tuần của năm (Chủ nhật là ngày đầu tiên của tuần). Tất cả các ngày trong một năm mới trước Chủ nhật đầu tiên được coi là vào tuần 0.00, 01, ..., 53
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())
0
Số tuần của năm (thứ Hai là ngày đầu tiên của tuần). Tất cả các ngày trong một năm mới trước ngày thứ Hai đầu tiên được coi là vào tuần 0.
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())
1
Đại diện ngày và thời gian thích hợp của địa phương.
Thứ Hai ngày 30 tháng 9 07:06:05 2013
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())
2
Đại diện ngày thích hợp của địa phương.
30/09/13
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())
3
Đại diện thời gian thích hợp của địa phương.

07:06:05

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
8

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())
4

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
9

Một nhân vật '%' theo nghĩa đen.


Phần trăm

Ví dụ 3: Ngày và giờ thích hợp của địa phương

Khi bạn chạy chương trình, đầu ra sẽ là:.

Mã định dạng

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())
1,
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())
2 và
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())
3 được sử dụng để biểu diễn ngày và thời gian thích hợp của địa phương.

Chúng tôi cũng đề nghị & nbsp; bạn kiểm tra Python Strptime (). Phương thức

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())
8 tạo đối tượng
Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
9 từ một chuỗi.

Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong python?

Chúng ta có thể chuyển đổi định dạng chuỗi thành DateTime bằng cách sử dụng hàm strptime (). Chúng tôi sẽ sử dụng định dạng '%Y/%M/%D' để đưa chuỗi vào DateTime ..

Đầu vào là chuỗi DateTime ..

Định dạng là định dạng-'Yyyy-MM-DD'.

DateTime là mô -đun ..

Làm thế nào để bạn thay đổi định dạng ngày từ một chuỗi trong Python?

Từ DateTime Nhập DateTime ..

date_time_str = '18/09/19 01:55:19 '.use the CONVERT() , TRY_CONVERT() , or CAST() function.

date_time_obj = DateTime. Strptime (date_time_str, '%d/%m/%y%h:%m:%s').

In ("Loại ngày là bây giờ", loại (DATE_TIME_OBJ)).

Làm cách nào để chuyển đổi DateTime sang định dạng ngày?

Để chuyển đổi DateTime thành một ngày, bạn có thể sử dụng hàm Convert (), try_convert () hoặc cast ().

Làm cách nào để thay đổi định dạng ngày từ yyyy mm dd trong gấu trúc?