简体   繁体   English

如何在python 2.7和python 3x中以时间戳(13位-毫秒)格式考虑上个月的第一天和上个月的最后一天?

[英]How to consider previous month first day and previous month last day in timestamp (13 digits--milliseconds) format in python 2.7 and python 3x?

Suppose today is August 28, 2019 i want timestamp of July 1,12:00:00 AM and July 31,23:59:59 PM . 假设今天是August 28, 2019我想要July 1,12:00:00 AMJuly 31,23:59:59 PM timestamp In general, I want the previous month date and time irrespective of year. 总的来说,我希望上个月的日期和时间与年份无关。

The following should work for both Python 3x and Python2.7 以下内容适用于Python 3x和Python2.7

from datetime import date
from dateutil.relativedelta import relativedelta

today = date.today()
d = today - relativedelta(months=1)

first_day = date(d.year, d.month, 1)
first_day.strftime('%A %d %B %Y')
#returns first date of the previous month - datetime.date(2019, 7, 1)

last_day = date(today.year, today.month, 1) - relativedelta(days=1)
last_day.strftime('%A %d %B %Y')

# returns the last date of the previous month - datetime.date(2019, 7, 31)

Note - The above code only returns the first and last date, not the time. 注意-上面的代码仅返回第一个和最后一个日期,而不是时间。 I don't really understand why can't you just hard code the time in milliseconds since it will always be fixed, irrespective of the date. 我真的不明白为什么您不能仅以毫秒为单位对时间进行硬编码,因为它总是固定的,而与日期无关。

Alternatively with no additional modules: 也可以不使用其他模块:

from datetime import datetime, timedelta
now = datetime.now()
print(now)
firstOfThisMonth = now.replace(day=1)
print(firstOfThisMonth)
endOfLastMonth = firstOfThisMonth-timedelta(days=1)
print(endOfLastMonth)
firstOfLastMonth = endOfLastMonth.replace(day=1)
print(firstOfLastMonth)
print(firstOfLastMonth.replace(hour=0, minute=0, second=0, microsecond=0))
print(endOfLastMonth.replace(hour=23, minute=59, second=59, microsecond=0))

Outputs the following 输出以下内容

2019-08-28 07:36:38.768223
2019-08-01 07:36:38.768223
2019-07-31 07:36:38.768223
2019-07-01 07:36:38.768223
2019-07-01 00:00:00
2019-07-31 23:59:59

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM