How to set a variable to be "Today's" date in Python/Pandas

175,223

Solution 1

You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime

>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')

This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.

Replacing today with now would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.

In pandas versions prior to 0.23.x, normalize may not have been necessary to remove the non-midnight timestamp.

Solution 2

If you want a string mm/dd/yyyy instead of the datetime object, you can use strftime (string format time):

>>> dt.datetime.today().strftime("%m/%d/%Y")
                   # ^ note parentheses
'02/12/2014'

Solution 3

Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")

Solution 4

pd.datetime.now().strftime("%d/%m/%Y")

this will give output as '11/02/2019'

you can use add time if you want

pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")

this will give output as '11/02/2019 11:08:26'

strftime formats

Solution 5

You can also look into pandas.Timestamp, which includes methods like .now and .today. Unlike pandas.to_datetime('now'), pandas.Timestamp.now() won't default to UTC:

  import pandas as pd

  pd.Timestamp.now() # will return California time
  # Timestamp('2018-12-19 09:17:07.693648')

  pd.to_datetime('now') # will return UTC time
  # Timestamp('2018-12-19 17:17:08')
Share:
175,223
Alexis
Author by

Alexis

Analyst at UC Berkeley using Python

Updated on July 05, 2022

Comments

  • Alexis
    Alexis almost 2 years

    I am trying to set a variable to equal today's date.

    I looked this up and found a related article:

    Set today date as default value in the model

    However, this didn't particularly answer my question.

    I used the suggested:

    dt.date.today
    

    But after

    import datetime as dt     
    date = dt.date.today
    print date
     <built-in method today of type object at 0x000000001E2658B0>
    
     Df['Date'] = date
    

    I didn't get what I actually wanted which as a clean date format of today's date...in Month/Day/Year.

    How can I create a variable of today's day in order for me to input that variable in a DataFrame?