Search code examples
pythonpython-3.xdatetimeutc

convert utc date time to utc timestamp in Python


I need to convert date time to UTC timestamp. but the problem is; different systems returns different timestamps based on machine timezone.

example: date1 = "2022-05-17 04:35:38"

UTC timestamp is: 1652762138

Code:

date1 = "2022-05-17 04:35:38"
date_utc = int(datetime.datetime.strptime(date1, '%Y-%m-%d %H:%M:%S').timestamp())

the problem as I mentioned is it returns number based on machine timezone.

I need simplest solution please.


Solution

  • I've found the solution so I'll post it here if anyone else got my problem:

    you can use timezone as:

    from datetime import datetime, timezone
    
    date1 = "2022-05-17 04:35:38"
    
    utc_timestamp = int(datetime.strptime(date1, '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc).timestamp())
    
    # will return 1652762138