Tuesday, May 20, 2014

Date in Python and its Conversion

Current date in Python using 'time' module

>>> import time
>>> time.strftime("format")
Ex:
>>> import time
>>> time.strftime("%d-%m-%Y")
'20-05-2014'
>>> time.strftime("%d-%m-%Y %H:%M:%S")
'20-05-2014 12:17:51'
Current date in Python using 'datetime' module

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2014, 5, 20, 12, 19, 16, 547221)
>>> now.year
2014
>>> now.month
5
>>> now.day
20
>>> now.hour
12
>>> now.minute
19
>>> now.second
16
>>> now.microsecond
547221
>>>
Change date format using time module

syntax:
time.strftime('required format', time.strptime('date data', 'source format'))
Ex:
>>> import time
>>> d1 = time.strftime('%d-%m-%Y', time.strptime('2014-05-10', '%Y-%m-%d'))
>>> d1
'10-05-2014'
>>>
Convert date to datetime using datetime module

Ex:
>>> from datetime import datetime
>>> d1 = datetime.strftime(datetime.strptime('2014-05-10', '%Y-%m-%d'), "%Y-%m-%d 00:00:00")
>>> d1
'2014-05-10 00:00:00'
>>> d2 = datetime.strftime(datetime.strptime('2014-05-10', '%Y-%m-%d'), "%Y-%m-%d 23:59:59")
>>> d2
'2014-05-10 23:59:59'
>>> d1, d2
('2014-05-10 00:00:00', '2014-05-10 23:59:59')
>>>

Labels: , , , , ,


0 comments: Post Yours! Read Comment Policy ▼
PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

 
Twitter Facebook RSS YouTube Google
© 2014 | Distributed and Designed By Jasad Moozhiyan