A Few (Simple) Type Conversions

Convert numbers (floating point numbers first).

In [20]:
pi = "3.14159"            # Approximately!  Don't be so literal. :)
print(type(pi))           
 
float_pi = float(pi)      # Convert to float
print(type(float_pi))     
print(float_pi)           

pi_again = str(float_pi)  # Convert BACK to string
print(type(pi_again))     
print(pi_again)
<class 'str'>
<class 'float'>
3.14159
<class 'str'>
3.14159

Can convert integers in similar way.

In [27]:
the_answer = "42"
int_answer = int(the_answer)
print(int_answer)

# Can't AUTOMATICALLY convert floats however, won't truncate, will throw exception.
pi = "3.14159"

# ERROR:  ValueError: invalid literal for int() with base 10: '3.14159'
# int(pi)

# To fix, convert to float first, then convert to int
# Did it as a one liner -- do I need to explain?
bald_pi = int(float(pi))  
print(bald_pi)
42
3

Dates and times (or "datetimes") are a bit more complex

Dates and times can be converted to strings using strftime. Hardest part about that is remembering the formatting characters "%<something". So don't try to remember them! Best bet is to look it up.

In [51]:
# Converting datetimes to strings 

import datetime

# Get an object representing the current date and time
date_and_time  = datetime.datetime.now()

# strftime can be read as string FORMAT time
# Converts a datetime to a string

print("Current time: " + date_and_time.strftime("%H:%M %m/%d/%Y") + "\n")

# strptime (String PARSE time) does the opposite.
print("'A date that will live in infamy.'")
datetime.datetime.strptime("07:48 12/07/1941", "%H:%M %m/%d/%Y")
Current time: 17:53 12/08/2017

'A date that will live in infamy.'
Out[51]:
datetime.datetime(1941, 12, 7, 7, 48)