python datetime to unix time, convert to string

2023. 3. 15. 20:29it

반응형

Today, I will summarize the basic syntax for converting datetime-related types in Python that I always search for on Google.

The syntax that I always look up is as follows: (It's difficult to memorize...><)

So, I have decided to summarize it myself this time!!!

The introduction was long. Let's get straight to the point.

1. Do "import datetime".

import datetime

2. To get the current time (current time / UTC time)

now = datetime.datetime.now()
utc = datetime.datetime.utcnow()

3. Let's try adding to a specific time.

Let's use timedelta to add values. Refer to the parameters below:

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

# add 10 seconds
time_sample = now + datetime.timedelta( seconds=10 )

print( time_sample )

>> 2021-07-17 00:18:56.488562

4. datetime to string

[Commonly used time format types]

2020-01-01 12:00:00.00 = '%Y-%m-%d %H:%M:%S.%f'

2020-01-01 12:00:00 = '%Y-%m-%d %H:%M:%S'

20200101120000 = '%Y%m%d%H%M%S'

# current time

now = datetime.datetime.now()

print( now )

>> 2021-07-17 00:18:56.488562

print( type( now ) )

>> <class 'datetime.datetime' >


# datetime to string

str_time = now.strftime('%Y-%m-%d %H:%M:%S.%f')

print( str_time )

>> 2021-07-17 00:18:56.488562

print( type( now ) )

>> <class 'str'>

5. string to datetime

[Commonly used time format types]

2020-01-01 12:00:00.00 = '%Y-%m-%d %H:%M:%S.%f'

2020-01-01 12:00:00 = '%Y-%m-%d %H:%M:%S'

20200101120000 = '%Y%m%d%H%M%S'

str_time = "2021-07-17 00:35:26.773934"

datetime_time = datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S.%f')

print( str_time )

>> "2021-07-17 00:35:26.773934"

6. Let's convert Unix time to datetime.

int_data = 1600000000

int_to_date = datetime.datetime.fromtimestamp(int_data)

print(int_to_date)

>> 2020-09-13 21:26:40

print( type(int_to_date) )

>> <class 'datetime.datetime'>

7. Let's convert datetime to Unix time.


To be precise, it is a float value rather than an integer...;;

print( int_to_date )

>> 2020-09-13 21:26:40

datetime_to_int = int_to_date.timestamp()

print( datetime_to_int )

>> 1600000000

print( type(datetime_to_int) )

>> <class 'flaot'>

8. Extracting date from datetime.

yyyy = int_to_date.year

mm = int_to_date.month

dd = int_to_date.day

hh = int_to_date.hour

mi = int_to_date.minute

ss = int_to_date.second

These are not difficult syntax, but I always look them up.

I have summarized the ones that I frequently use, so it would be helpful to refer to them.

All the code has been tested, so there should be no issues.

That's it for now.!!

반응형