以周三为例,根据当前时间点,获取下一次最近的周三日期
def get_wednesday_date():
today = date.today()
days = 2 - today.weekday()
time_delta = timedelta(days=days) if days > 0 else timedelta(days=7+days)
return today + time_delta
可以就代码风格和实现讨论,提供更 pythonic 的想法
1
luosch 2016-11-28 17:43:06 +08:00
```python
def get_wednesday_date(): return date.today() + timedelta(((2 - date.today().weekday()) + 7) % 7) ``` |
2
tumbzzc 2016-11-28 18:04:13 +08:00
import datetime
now=datetime.datetime.now() dayslater=now+datetime.timedelta(7) print(dayslater.strftime('%Y%m%d')) |
3
Jakesoft 2016-11-28 18:04:44 +08:00
php:
datetime('Y-m-d H:i:s', strtotime('next Wednesday')); |
4
l9rw 2016-11-28 19:13:50 +08:00
@Jakesoft php 原生没有 datetime 函数吧。 echo date('Y-m-d', strtotime('next Wednesday'));
|
5
Contextualist 2016-11-28 20:12:30 +08:00 via iPad
def get_wednesday_date():
today = datetime.datetime.today().isoweekday() time_delta = timedelta(date=3 - today + (3<today) * 7) return today + time_delta |
6
tumbzzc 2016-11-28 21:08:39 +08:00
搞不懂~我的不是最简洁的吗?
|
7
0915240 2016-11-28 22:53:18 +08:00
```jodatime or javase8
LocalDate localDate = LocalDate.now(); System.out.println(localDate.with(DayOfWeek.WEDNESDAY).plusWeeks(1)); ``` |
9
slixurd 2016-11-29 01:00:20 +08:00
给另一个 Joda Time 的写法
DateTime nextWednesday = new DateTime().withDayOfWeek(3).plus(Weeks.ONE); |
10
zzyzxd 2016-11-29 04:00:29 +08:00
```
>>> import parsedatetime >>> cal = parsedatetime.Calendar() >>> cal.parse("next Wednesday") (time.struct_time(tm_year=2016, tm_mon=12, tm_mday=7, tm_hour=9, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=342, tm_isdst=-1), 1) >>> cal.parse("this coming wednesday") (time.struct_time(tm_year=2016, tm_mon=11, tm_mday=30, tm_hour=19, tm_min=59, tm_sec=28, tm_wday=2, tm_yday=335, tm_isdst=-1), 1) ``` (逃…… |
11
pppy OP 感觉 @Contextualist 的比较清真
|
12
FreeBTC123 2016-11-29 14:26:22 +08:00
* 安装
```shell pip install isoweek ``` * 使用 ```python In [1]: from isoweek import Week In [2]: (Week.thisweek() + 1).wednesday() Out[2]: datetime.date(2016, 12, 7) ``` |
13
FreeBTC123 2016-11-29 14:30:16 +08:00
囧, 搞成下周的周三了
|
14
FreeBTC123 2016-11-29 14:55:25 +08:00
```python
In [1]: from datetime import datetime In [2]: from isoweek import Week In [3]: def coming_weekday(num): ...: this_week = Week.thisweek() ...: this_weekday = this_week.day(num) ...: return this_weekday if this_weekday > datetime.now().date() else (this_week + 1).day(num) ...: In [4]: coming_weekday(2) Out[4]: datetime.date(2016, 11, 30) In [5]: # 0 is Monday ``` |
15
FreeBTC123 2016-11-29 15:09:27 +08:00
```python
In [13]: def coming_weekday(num): this_week = Week.thisweek() return (this_week + (not this_week.day(num) > datetime.now().date())).day(num) ....: ``` |