Python [conda default] v3.6

Pandas - Working w DateTimes

Related Articles and Posts On The Web:

Code Samples - DateTime In General

This code can be used independantly of Pandas, but could also be used to populate a Pandas DF column.


In [4]:
d1 = '2018-01-31'
year, month, day = d1.split('-')
print(year)
print(month)
print(day)


2018
01
31

In [6]:
import datetime
myDate = datetime.datetime.strptime(d1, "%Y-%m-%d")
myDate


Out[6]:
datetime.datetime(2018, 1, 31, 0, 0)

In [9]:
print(myDate.day, "\n", myDate.month, "\n", myDate.year)


31 
 1 
 2018

In [1]:
## this example comes from some of my code
#  It successfully generates the kind of now() I wanted and uses EST on my computer
#  based on how it is written, it should use Pacific or other timezones if run on a computer
#  in those time zones:

# note: gmtime() produced results in Grenwich Mean Time
#       localtime() seems to get the local time from the computer (in my case EST)

from time import localtime, strftime

def getNow():
    return strftime("%Y-%m-%d %H:%M:%S", localtime())

In [2]:
getNow()


Out[2]:
'2018-06-07 16:04:45'

Accessing System Time

Content taken from here.


In [5]:
>>> from datetime import datetime
>>> str(datetime.now())


Out[5]:
'2018-06-04 15:38:42.086974'

In [4]:
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())


Out[4]:
'2018-06-04 19:38:33'

In [3]:
>>> from datetime import datetime
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')


Out[3]:
'2018-06-04 15:37:29'

In [6]:
>>> import datetime
>>> datetime.datetime.now()


Out[6]:
datetime.datetime(2018, 6, 4, 15, 39, 25, 445666)

In [8]:
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)


Out[8]:
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

In [9]:
from datetime import datetime
datetime.now().time()


Out[9]:
datetime.time(15, 40, 32, 759258)

In [11]:
# combining some of the above:
datetime.now().time().strftime('%H:%M:%S')


Out[11]:
'17:18:54'

In [12]:
datetime.now().date().strftime('%Y-%m-%d')


Out[12]:
'2018-06-04'

In [ ]: