Adding Dates and Times in Python
Using the built-in modules datetime and timedelta, you can perform date and time addition/subtraction in python:
- from datetime import datetime
- from datetime import timedelta
- #Add 1 day
- print datetime.now() + timedelta(days=1)
- #Subtract 60 seconds
- print datetime.now() - timedelta(seconds=60)
- #Add 2 years
- print datetime.now() + timedelta(days=730)
- #Other Parameters you can pass in to timedelta:
- # days, seconds, microseconds,
- # milliseconds, minutes, hours, weeks
- #Pass multiple parameters (1 day and 5 minutes)
- print datetime.now() + timedelta(days=1,minutes=5)
Here is a python reference that gives more examples and advanced features:
http://docs.python.org/library/datetime.html
If you are coming from a .net or sql environment, here are the above examples in C# and SQL (Microsoft) for comparison:
C#
- DateTime myTime = new DateTime();
- --Add 1 day
- myTime.AddDays(1);
- --Subtract 60 seconds
- myTime.AddSeconds(-60);
- --Add 2 years
- myTime.AddYears(2);
SQL
- --Add 1 day
- select DATEADD(day, 1, getdate())
- --Subtract 60 seconds
- select DATEADD(second, -60, getdate())
- --Add 2 years
- select DATEADD(Year, 2, getdate())
'C Lang > Python Program Diary' 카테고리의 다른 글
python에서 변수나 리턴의 타입을 지정 : typing, NewType, generics, (0) | 2019.10.21 |
---|---|
파이썬의 시간대에 대해 알아보기, naive datetime, aware datetime (0) | 2019.10.09 |
【PythonのORM】ORM이란, ORM의 장단점, ORM프레임워크인 SQLAlchemy의 기본 사용법 정리 (0) | 2019.10.02 |
나만의 파이썬 패키지를 작성하는 법 (0) | 2019.09.24 |
RESTful API Designing guidelines — The best practices (0) | 2019.09.09 |
Mon, Oct 19, 2009
Tech Tips